我正在使用 Angular 9 应用程序,并且仅当我的应用程序状态(ngrx)具有属性时才尝试加载(或不加载)特定模块!= null
首先,我的路线中有一个 AuthGuard,但带有 canActivate。所以我希望“仪表板”模块仅在 mt AppState 有令牌时加载
这是我的路线文件
const routes: Routes = [
{
path: '',
component: AppLayoutComponent,
canActivate: [ AuthGuard ],
children: [
{ path: '', loadChildren: () => import('./pages/modules/dashboard/dashboard.module').then(m => m.DashboardModule) }
]
},
{
path: '',
component: AuthLayoutComponent,
children: [
{ path: 'session', loadChildren: () => import('./pages/modules/session/session.module').then(m => m.SessionModule) }
]
},
{
path: '**',
redirectTo: 'session/not-found'
}];
这是我的 AuthGuard。它 localestorage 没有会话,然后重定向到登录页面。
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, public authService: AuthService) {}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (localStorage.getItem('session')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['session/signin']);
return false;
}
}
这是我想要在 AuthModuleGuard 中使用 canLoad 做的事情,但这不起作用
public canLoad(): Observable<boolean> {
return this.store.select('session').pipe(
take(1),
map((authstate) => {
console.log('Token status', authstate.token);
if (authstate.token !== null) {
return true;
} else {
this.router.navigate(['session/signin']);
return false;
}
})
);
}
如果我这样做......应用程序给了我错误并且仍然加载两个文件
{
path: '',
component: AppLayoutComponent,
canLoad: [ AuthModuleGuard ],
children: [ ... ]
}
如果我这样做......应用程序永远不会完成加载
{ path: '', canLoad: [ AuthModuleGuard ], loadChildren: () => import('./pages/modules/dashboard/dashboard.module').then(m => m.DashboardModule) },
这是一个 STACKBLITZ 示例(包括我的文件夹结构)---> https://stackblitz.com/edit/angular-ivy-nasx7r
仅当我的商店中的令牌已设置时,我才需要一种加载仪表板模块(和其他模块)的方法,如果未设置,则重定向到登录。请帮忙