首页 > 解决方案 > 在 canActivateChild 返回 true/false 之前,正确等待多个可观察对象在路由保护中返回数据

问题描述

我的 canActivateChild 路由守卫在确定是否可以激活路由之前没有等待数据从 3 个服务调用返回到后端时遇到问题。我将它连接到 ngRx 存储中并分派 3 个单独的操作,然后使用 forkJoin 返回我认为的 Observable 内容,以确定它们是否都返回数据。这似乎无法正常工作,因为这 3 个中的一个通常在组件中返回 undefined。

据我了解,选择返回一个可观察对象,并且 filter/take(1) 确保满足条件后可观察对象完成。这似乎工作正常,因为它在过滤器中多次命中,最终获得其中 2 个的数据。我不明白如果其中一项没有返回数据,为什么它会返回 true。

关于如何使其正常工作的任何帮助?

getFromStoreOrAPI(): Observable<any> {
   return forkJoin(
      this.store.select(getFinancialFactors).pipe(filter(financialFactors => financialFactors && financialFactors.length > 0), take(1)),
      this.store.select(getFinancialData).pipe(filter(financialData => financialData && financialData.length > 0),take(1)),
      this.store.select(getFranchiseData).pipe(filter(franchiseData => franchiseData && franchiseData.length > 0),take(1))
   );
}

canActivateChild(route: ActivatedRouteSnapshot): Observable<boolean> | boolean {
    let tranId = this.router.getCurrentNavigation().extras.state.tranId;
    let modelId = this.outer.getCurrentNavigation().extras.state.modelId;

    this.store.dispatch(ScorecardActions.loadFinancialData({tranId: tranId}));
    this.store.dispatch(ScorecardActions.loadFranchiseData({tranId: tranId}));
    this.store.dispatch(ScorecardActions.loadFinancialFactors({modelId: modelId}));

    return this.getFromStoreOrAPI()
    .pipe(
        switchMap(() => of(true)),
        catchError(() => of(false))
     );
   }
}

标签: angularrxjsngrx-storeangular-route-guards

解决方案


推荐阅读