【发布时间】: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