【发布时间】:2018-03-12 09:23:19
【问题描述】:
我想知道是否有办法在保护完成之前阻止组件加载?
问题
我的组件在警卫检索有关用户的相关信息之前加载,因此加载检查失败。
我目前的设置如下:
应用路由模块
{
path: 'sub', component: MasterComponent, canActivateChild: [AuthGuard],
children: [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent }
]
},
AuthGuard - canActivateChild 方法
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.secService.isAuthorized()
.map((profilePresent: boolean) => {
if (!profilePresent) {
this.secService.getProfile().subscribe(
(data: any) => {
sessionStorage.setItem('profile', JSON.stringify(data));
return false;
}
);
return true;
}
this.secService.redirectToAuthorization();
return false;
});
}
在我的 Dashboard.component.ts 中:
ngOnInit() {
var name = JSON.parse(sessionStorage.getItem('profile')).name;
console.info(name);
}
这一切都会在控制台上引发错误:
ERROR TypeError: Cannot read property 'name' of null
跟踪它我注意到在组件加载之前防护没有完成,因此出现错误(它当时不存在)。
关于如何管理的任何想法
【问题讨论】:
-
还有
canLoad、CanActivate和Resolve。也许其中之一会帮助你。