代码之家  ›  专栏  ›  技术社区  ›  prabhat gundepalli

通过NGRX选择检查多个值的保护

  •  1
  • prabhat gundepalli  · 技术社区  · 8 年前

    我有一个canactivate(guard),在这里我检查加载的变量,看看队列是否加载了。

    不过,我现在需要检查多个队列加载变量(布尔值),看看它们是否都已加载。那我就得采取行动了。

        canActivate(): Observable<boolean> {
    return this.checkStore().pipe(
      switchMap(() => of(true)),
      catchError(() => of(false))
    );
    }
    
      checkStore(): Observable<boolean> {
    //   Below are the additional booleans I need to check on
    //  this.store.select(fromStore.isFirstQueueLoaded);
    //  this.store.select(fromStore.isSecondQueueLoaded);
    //  this.store.select(fromStore.isThirdQueueLoaded);
    //  this.store.select(fromStore.isFourthQueueLoaded);
    //  this.store.select(fromStore.isFifthQueueLoaded);
    //  this.store.select(fromStore.isSixthQueueLoaded);
    //  this.store.select(fromStore.isSeventhQueueLoaded);
    
    
      return this.store.select(fromStore.isFirstQueueLoaded)
      // want to check for remaining queues loaded boolean val here
      .pipe(
      tap(loaded => {   
         // need to check for loaded values of all queues
        if (!loaded) {
          this.dispatchActiontoStoreForAllQueue();
        }
      }),
      filter(loaded => loaded)
      );
     }
    
    dispatchActiontoStoreForAllQueue(): void {
    this.store.dispatch(new fromStore.LoadFirstQueue({}));
    this.store.dispatch(new fromStore.LoadSecondQueue({}));
    this.store.dispatch(new fromStore.LoadthirdQueue({}));
    this.store.dispatch(new fromStore.LoadFourthQueue({}));
    this.store.dispatch(new fromStore.LoadFifthQueue({}));
    this.store.dispatch(new fromStore.LoadSixthQueue({}));
    this.store.dispatch(new fromStore.LoadSeventhQueue({}));
     }
    

    我们如何结合所有这些NGRX选择(优化方法)检查他们的布尔和激活警卫?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Teddy Sterne    8 年前

    我将创建一个选择器,而不是七个不同的选择器。这看起来像是:

    export const fromStore = {
      areAllQueuesLoaded: createSelector(selectAppState, (state: AppState) => {
        return state.queue1.isLoaded &&
               state.queue2.isLoaded &&
               state.queue3.isLoaded &&
               state.queue4.isLoaded &&
               state.queue5.isLoaded &&
               state.queue6.isLoaded &&
               state.queue7.isLoaded;
      }),
    }
    

    然后在组件中,您只需要选择一个:

    return this.store.select(fromStore.areAllQueuesLoaded).subscribe(loaded => {   
        this.dispatchActiontoStoreForAllQueue();
    });
    
    推荐文章