在路由器导航上不调用LifeCycle调用

问题描述 投票:0回答:1

我已经设置了这条路线

{path:'home', component:HomeComponent, canActivate: [AuthGuard]},  
{path:'profile', component:UserProfileComponent, canActivate: [AuthGuard] },

在我的navbar.component中我有以下内容

        <li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}">
            <a [routerLink]="['/home']" class="nav-link"><i class="fas fa-home fa-2x"></i></a>
        </li>
        <li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}">
            <a [routerLink]="[ '/profile']" class="nav-link"><i class="fas fa-user fa-2x"></i></a>
        </li>

在我的home.component我从ngOnInit()中的firebase服务获取数据

ngOnInit() {
    this.firebaseService.getPodcasts().subscribe(podcasts => {
      this.podcasts = podcasts;
    });

这只发生在第一次我导航到家,但如果我去配置文件(从导航栏)然后回到家,ngOnInit没有被调用(我试图控制日志里面没有任何反应)。但是当我编写例如https://localhost/4200/home的URL时,它会激活ngOnInit()生命周期。

我不确定这是多么相关,但这是我的app.component的HTML:

<div class="app-container">

    <app-navbar *ngIf="authService.getAuthState()" (updateSideNav)='toggleSideNavParent($event)'>
    </app-navbar>
    <flash-messages></flash-messages>

    <router-outlet>
    </router-outlet>
</div>
<div *ngIf="authService.getAuthState()" class="sidenav-overflow" [ngClass]="{'show-overflow':isSideNavOpen}">
    <app-sidenav [isSideNavOpen]='isSideNavOpen'></app-sidenav>
</div>

在我的home.component:

<div class="jumbotron">
<h1>home</h1>
    <app-record></app-record>
    <app-content [allPodcasts]="podcasts"></app-content>
</div
angular angular2-routing lifecycle angular4-router
1个回答
0
投票

好的,问题不在于ngOnInit,而在于firebaseFirestore。每当我加载ngOnInit并调用

this.firebaseService.getPodcasts().subscribe(podcasts => {
      this.podcasts = podcasts;
    });

它从来没有因为某种原因而调用它。但我改变了firebaseService.getPodcasts()

public getPodcasts(){
      return this.podcasts;
    }

至:

 public getPodcasts(){
  this.podcasts = this.podcastCollection.snapshotChanges().map(changes => {
    return changes.map(a => {
      const data = a.payload.doc.data() as Podcast;
      data.id = a.payload.doc.id;
      return data;
    })
  })
  return this.podcasts;
}

现在它工作..我仍然不明白为什么因为在我设置的firebaseService构造函数

this.podcasts = this.podcastCollection.snapshotChanges().map(changes => {
    return changes.map(a => {
      const data = a.payload.doc.data() as Podcast;
      data.id = a.payload.doc.id;
      return data;
    })
  })
© www.soinside.com 2019 - 2024. All rights reserved.