【问题标题】:LifeCycle calls are not called on router navigation路由器导航不调用 LifeCycle 调用
【发布时间】:2017-12-21 10:11:22
【问题描述】:

我已经设置了这条路线

{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

【问题讨论】:

  • 当您在地址栏中键入路由时 - 它会转到服务器 - 因此应用程序正在从头开始重新创建。顺便说一句,你为什么使用 ngOnInit?你能在构造函数中做同样的调用吗?
  • 是的,我在构造函数中尝试过,但我遇到了同样的问题。当我在路由之间导航时它不会调用构造函数。

标签: angular angular2-routing lifecycle angular4-router


【解决方案1】:

好的,所以问题不在于 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;
    })
  })

【讨论】:

    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2015-03-14
    • 2018-02-22
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多