5

我正在使用 @ngrx/store 来检查状态是否已经加载,并且我遇到了一个问题,即canActivate如果我使用过滤器,该方法永远不会返回。

这是 GetCompanies 操作的示例效果:

return this.companiesService.getCompanies()
  .pipe(
    map(companies => new companiesActions.GetCompaniesSuccess(companies)),
    catchError(error => Observable.of(new companiesActions.GetCompaniesFail(error)))
  )

如果出现错误,我将发送 GetCompaniesFail 操作并将用户重定向到/login页面。没关系,有趣的部分是守卫。

@Injectable()
export class CompaniesGuard implements CanActivate {
  constructor(
    private store: Store<AppState>,
    private router: Router
  ) {}

  canActivate(): Observable<boolean> {
    return this.checkStore()
      .pipe(
        switchMap(() => Observable.of(true)),
        catchError(() => Observable.of(false))
      );
  }

  checkStore(): Observable<boolean> {
    return this.store.select(getCompaniesLoaded)
      .pipe(
        tap(loaded => {
          if (!loaded) {
            this.store.dispatch(new companiesActions.GetCompanies());
          }
        }),
        filter(loaded => loaded),
        take(1)
      );
  }
}

如果出现错误并且加载不为假,则canActivate不会返回任何内容,因为checkStore什么也不做。

如果我更改filtermap它可以工作,但它只需要第一个值,false即使数据将成功加载。

我错过了什么?我该如何处理那里的 HTTP 错误?有没有办法等待特定状态或在内部抛出错误checkStore

预先感谢!

4

1 回答 1

1

如果您将职责分开一点,这似乎更容易处理。

无论如何,您都应该运行checkStore,而不是直接依赖它的结果。相反,让商店通知您成功或失败并返回该结果。

请注意,ngrx 和 redux 鼓励使用单向数据流来简化应用程序逻辑。

store 属性getCompaniesLoadedStatus初始化为initial ,并在or内设置为successfailedcompaniesActions.GetCompaniesSuccesscompaniesActions.GetCompaniesFail

重试在服务中处理(更接近获取)。

canActivate(): Observable<boolean> {
  this.checkStore();
  return this.store.select(getCompaniesLoadedStatus).pipe(
    filter(status => status !== 'initial'),
    map(status => status === 'success' ? true : false )
  );
}

checkStore(): void {
  this.store.select(getCompaniesLoadedStatus).pipe(
    take(1)  // so that unsubscribe is not needed
  ).subscribe(status =>
    if (status === 'initial') { 
      this.store.dispatch(new companiesActions.GetCompanies());
    }
  );
}
于 2018-02-12T22:16:54.700 回答