拜托,我实际上有一个app.module,它通过延迟加载来加载核心模块。我将核心组件中的角色加载到商店中。然后我有一个角色警卫进入商店查看这些角色。当我加载一些 /home 页面,然后转到应用了角色防护的页面时,一切正常,因为角色已经加载。然而,当我直接在浏览器中输入角色防护所应用的 URL 时,它就搞砸了。它加载app.module,但随后它不再加载core.module,而是加载guard。角色不在哪里,甚至当我通过跳过这样尝试时,它仍然不起作用。知道该怎么办吗?非常感谢
应用程序路由模块
{
path: '',
children: [{
path: '', loadChildren: () => import('./core/core.module').then(m => m.CoreModule)
}]
},
核心路由模块
{
path: '',
component: CoreComponent,
children: [
{
path: "test,
loadChildren: () => import('@modules/test/test.module').then(m => m.TestModule),
canActivate: [MyGuard]
......
核心组件
ngOnInit(): void {
this.authFacade.initAll();
this.authFacade.loginCheck();
}
AuthGuard - 仅用于测试
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.authFacade.user$.pipe(
skipWhile(user => user === undefined),
take(1),
map(user => {
console.log(user);
if (!user)
return false;
return true;
})
)
}
这可能是因为角色正在您的CoreComponent
中
异步加载,并且在获取和存储角色之前正在评估守卫。你可以试试这个:
//CoreComponnet
ngOnInit(): void {
this.authFacade.initAll();
this.authFacade.loginCheck();
this.authFacade.rolesLoaded$.pipe(
// wait until roles are loaded
filter(loaded => loaded),
// only happens once
take(1)
).subscribe(() => {
// roles loaded
});
}
和
//AuthGuard
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return combineLatest([
this.authFacade.user$,
// something to track roles loading
this.authFacade.rolesLoaded$
]).pipe(
skipWhile(([user, rolesLoaded]) => user === undefined || !rolesLoaded),
take(1),
map(([user, rolesLoaded]) => {
if (!user) {
return false;
}
// check user's roles against necesary roles for the route
// add logic here to see if the user has the required roles
return true;
})
);
}