3

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

我有 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发出任何动作。我在这里错过了什么吗?而且我想知道这是否是一个好习惯?我确实找到了一些canActivate守卫用法的例子,但没有找到守卫的例子canLoad。请帮忙,谢谢!

4

1 回答 1

9

经过一整天的调试,我终于弄明白了!修复非常简单,添加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));
}

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

于 2017-11-01T06:53:05.900 回答