刷新页面时,未定义通过路径数据属性传递的数据。我正在使用路由保护并基于模块的privilegeId,canActivate返回Observable boolean。
home.routing.ts
export const HomeRoutes: Routes = [
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{ path: '', component: DashboardComponent },
{
path: 'groups',
loadChildren: 'app/modules/groups/groups.module#GroupsModule',
data: { privilegeId: 5 }
}
]
},
];
export const HomeRouting = RouterModule.forChild(HomeRoutes);
AUTH-guard.service.ts
canActivate(routeSnapshot: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
// Issue: privilegeId is undefined on page reload.
let privilegeId = routeSnapshot.data["privilegeId"] as number;
// Calls API with privilege id and returns boolean.
}
不知何故,刷新后你无法访问父母看守中的路线数据。
首先,保护孩子路线的最佳方法是使用canActivateChild
而不是canActivate
。
现在奇怪的是,仅在刷新之后,ActivatedRouteSnapshot
不在当前路线的范围内,这意味着当前路线没有路线数据。
幸运的是,完整的路线包含在RouterStateSnapshot
-Property中的root
中,这是一棵树。
您现在可以沿着这棵树(每个只包含一个孩子)走下去,看看其中一个孩子是否有任何数据:
searchData(state: RouterStateSnapshot, dataKey: string): string | null {
if (state.root.data && state.root.data[dataKey])
return state.root.data[dataKey];
let child: ActivatedRouteSnapshot | null;
child = state.root.firstChild;
while (child != null) {
if (child.data && child.data[dataKey]) {
return child.data[dataKey];
}
child = child.firstChild;
}
return null;
}
此方法在RouterStateSnapshot
中搜索具有指定键的数据,并返回第一次出现(如果有)或null