gpt4 book ai didi

angular - 如何使 ngrx-store 与 canLoad 防护一起使用

转载 作者:行者123 更新时间:2023-12-03 23:37:42 25 4
gpt4 key购买 nike

我不知道这是否是一个好习惯。但以下是我想要做的:

我有2个懒加载模块:ManagementModuleConfigurationModule,路由配置如下:

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 Action 。我在这里错过了什么吗?而且我想知道这是否是一个好习惯?我确实找到了一些 canActivate 防护使用示例,但没有找到 canLoad 防护。请帮忙,谢谢!

最佳答案

经过一整天的调试,我终于弄明白了!修复很简单,在 filter() 之后添加 first()take(1) 到运算符链中,我无法表达我现在有这种感觉......但我确实意识到我需要改变思维方式才能正确使用 RxJS。

canLoad(route) {
this.store.dispatch(new CheckInitStatus());
return this.store.select('initStatus')
.filter(s => s.checked) // check only when loaded
.first() // or equivalently take(1)
.map(s => s.status === 'initialized')
.catch(() => of(false));
}

我应该仔细阅读canActivate的例子,这个take(1)/first()操作符都在那里,例如:https://toddmotto.com/preloading-ngrx-store-route-guards

关于angular - 如何使 ngrx-store 与 canLoad 防护一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com