我不知道这是否是一个好习惯。但以下是我正在尝试做的事情:
我有 2 个延迟加载的模块:ManagementModule
和ConfigurationModule
,并且路由配置如下:
const routes: Routes = [
{path: '', redirectTo: 'management', pathMatch: 'full'}, {
path: 'configuration',
loadChildren: './configuration/configuration.module#ConfigurationModule',
canLoad: [UnconfiguredGuard]
},
{
path: 'management',
loadChildren: './management/management.module#ManagementModule',
canLoad: [ConfiguredGuard]
}
]
基本上这个想法是检查系统状态并重定向到不同的阶段,例如。如果 sys 尚未配置,则重定向到/configuration
,否则,重定向到/management
.
在我添加@ngrx/store
到项目之前,这两个canLoad
守卫很简单:
// ConfiguredGuard:
canLoad(route) {
return this.configService.isConfigured()
.do((configured: boolean) => {
if (!configured) {
// redirect to /configuration if unconfigured
this.router.navigate(['/configuration']);
}
})
}
现在我想采用所有 @ngrx/{store,effects,router-store} 库,然后将上面的守卫更改为:
canLoad(route) {
this.store.dispatch(new CheckInitStatus());
return this.store.select('initStatus')
.filter(s => s.checked) // check only when loaded
.map(s => s.status === 'initialized')
.catch(() => of(false));
}
当然,副作用是定义的:
@Effect()
check$: Observable<InitStatusAction> = this.actions$
.ofType<CheckInitStatus>(CHECK_INITSTATUS)
.mergeMap(() => this.fetchInitStatus())
.map(status => new InitStatusChecked({status, checked: true}))
.catch(e => of(new InitStatusCheckFailure(e)));
但是导航没有发生,没有ROUTER_NAVIGATION
发出任何动作。我在这里错过了什么吗?而且我想知道这是否是一个好习惯?我确实找到了一些canActivate
守卫用法的例子,但没有找到守卫的例子canLoad
。请帮忙,谢谢!