如何使Ngrx-store与canLoad Guard一起使用

Roy*_*ing 2 ngrx ngrx-effects angular ngrx-store-4.0

我不知道这是否是个好习惯。但是下面是我想做的事情:

我有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]
  }
]
Run Code Online (Sandbox Code Playgroud)

基本上,该想法是检查系统状态并重定向到不同的阶段,例如。如果尚未配置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']);
          }
        })
}
Run Code Online (Sandbox Code Playgroud)

现在,我要采用所有@ 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));
}
Run Code Online (Sandbox Code Playgroud)

当然,副作用定义为:

  @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)));
Run Code Online (Sandbox Code Playgroud)

但是导航没有发生,没有ROUTER_NAVIGATION发出任何动作。我在这里想念什么吗?我也想知道这是否是一个好习惯?我确实找到了一些canActivate使用守卫的例子,但没有一个可以用作canLoad守卫。请帮忙,谢谢!

Roy*_*ing 7

经过一整天的调试,我终于明白了!不过,修复非常简单,在之后添加first()或添加take(1)到运算符链中filter(),我无法表达自己的感觉...但是我确实意识到我需要改变思维方式才能正确使用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));
}
Run Code Online (Sandbox Code Playgroud)

我应该canActivate更仔细地阅读示例,该take(1)/first()运算符就在那儿,例如:https : //toddmotto.com/preloading-ngrx-store-route-guards