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

时间:2017-12-21 10:11:23

标签: angular angular2-routing lifecycle angular4-router

我已设置此路线

{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

1 个答案:

答案 0 :(得分: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;
    })
  })