我有按钮调用routerLink
来加载我<router-outlet>
的不同视图,如下所示:
<div style="padding-left: 20px; padding-top: 20px;" >
<router-outlet></router-outlet>
</div>
<mat-drawer #drawer class="example-sidenav" mode="side" opened=true>
<div>
<mat-divider style="width: 100%"></mat-divider>
</div>
<br>
<div>
<button mat-fab color="warn" [routerLink]="['/account']">
<mat-icon color="white">accessibility</mat-icon>
</button>
</div>
<br>
<div>
<button mat-fab color="warn" [routerLink]="['/others']">
<mat-icon color="white">accessibility</mat-icon>
</button>
</
</mat-drawer>
这应该仅在第一次加载主要组件时发生。
之后应该只加载不同的视图或子组件。在ngOnInit
我从api加载一些数据,所以我可以将它放在我的导航栏中,如下所示:
HTML
<span>{{userInfo?.FirstName}} {{userInfo?.LastName}} | </span>
TS
ngOnInit() {
debugger;
this.userService.getUserInfo()
.subscribe((data: any) => {
this.userInfo = data;
this.userInfo.SignInTime = localStorage.getItem('signInTime');
console.log(this.userInfo);
});
}
这是我的路由器:
export const appRoutes: Routes = [
{path: 'main', component: MainComponent, canActivate: [AuthGuard]},
{path: 'account', component: MainComponent,
children: [
{path: '', component: AccountComponent}
]
},
{path: 'others', component: MainComponent,
children: [
{path: '', component: OthersComponent}
]
},
{path: 'register', component: RegisterloginComponent,
children: [
{path: '', component: RegisterComponent}
]
},
{path: 'login', component: RegisterloginComponent,
children: [
{path: '', component: LoginComponent}
]
},
{path: '', redirectTo: '/login', pathMatch: 'full'}
];
问题是;每当我点击其中一个链接时,总会调用ngOnInit,从而使我的导航栏闪烁,因为它再次获取信息。你能告诉我如何纠正这个问题。谢谢。
答案 0 :(得分:1)
您正在并行组织所有路由,因此即使它们转到MainComponent
,路由器也会销毁并重新创建这些组件。如果您想保留组件,则需要在一棵树中组织通过MainComponent
的所有路由。
{
path: 'main',
component: MainComponent,
children: [
{
path: '',
pathMatch: 'full',
canActivate: [AuthGuard],
component: SomeEmptyComponent,
},
{
path: 'account',
component: AccountComponent,
},
{
path: 'others',
component: OthersComponent,
},
],
}
请注意,这会将路由从/account
更改为/main/account
。还有其他方法来设计路线,但最终路由器必须能够确定要做什么。此外,您至少需要一些空组件才能加载到/main
路由的路由器插座。
保持当前路由设计的另一种方法是使用服务来缓存闪烁的信息。
旁注,/main
有一个身份验证后卫似乎很奇怪,但/account
和/others
没有。这可能是个错误。