首页 > 解决方案 > 如何在 Angular Guard 中使用 CombineLatest 和 Ngrx

问题描述

我正试图等待几个状态true在我的保护之下。

我试过这样:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return combineLatest([
      this.store.select(
        fromStore.selectProductsLoaded
      ),
      this.store.select(fromStore.selectArticlesLoaded),
    ]).pipe(
      map(([a, b]) => ({ a, b })),
      filter(({ a, b}) =>  a && b),
      first()
    );
  }

我需要这两个数据,true所以我想使用combineLatest但遇到了这个错误: Type 'Observable<{ a: boolean; b: boolean; }>' is not assignable to type 'Observable<boolean>'

相比之下,这有效:

    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return  this.store
      .select(fromStore.selectProductsLoaded)
      .pipe(
        filter((loaded) => loaded),
        take(1)
      );
  }

标签: angularrxjs

解决方案


你得到这个错误的原因是因为使用 combineLatest 你传递了一个 observables 数组,然后将它映射到结构 {a: boolean, b: boolean} 的对象。

我猜你想根据这两个输入返回一个布尔值。

所以一个可能的解决方案可能是

.pipe(
      map(([a, b]) => ({ a, b })),
      filter(({ a, b}) =>  a && b),
      map(values => {
        // both a and b are true
        if(values.a && values.b){
          return true;
        } else {
          return false;
        }
      }),
      first()
    );

推荐阅读