我有按钮调用 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,从而使我的导航栏闪烁,因为它再次获取信息 . 你能告诉我如何纠正这个问题 . 谢谢 .
1 回答
您正在并行组织所有路由,因此即使它们转到
MainComponent
,路由器也会破坏并重新创建这些组件 . 如果要保留组件,则需要在一棵树中组织所有路径MainComponent
.请注意,这会将路径从
/account
更改为/main/account
. 还有其他方法来设计路线,但最终路由器必须能够确定要做什么 . 此外,您至少需要一些空组件才能加载到/main
路由的路由器插座中 .保持当前路由设计的另一种方法是使用服务来缓存闪烁的信息 .
旁注,
/main
有一个auth后卫似乎很奇怪,但/account
和/others
没有 . 这可能是个错误 .