如何使 ngrx-store 与 canLoad guard 一起工作



我不知道这是否是一个好的做法。但以下是我正在尝试做的事情:

我有 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} libs,然后将上面的保护更改为:

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守卫的例子。请帮忙,谢谢!

经过一整天的调试,我终于想通了!修复很简单,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

最新更新