【问题标题】:NGRX Get State from Parameterized Selector in EffectNGRX 从有效的参数化选择器获取状态
【发布时间】:2019-03-18 05:14:29
【问题描述】:

背景

我有一个用于搜索的 NGRX 商店,如下所示:

export interface State {
   field: string;
   operator: string;
   criteria: string;
   offset: number;
   limit: number;
}

而且因为我对 Search 有多种用途,所以我在我的主状态对象中创建了这个 Search 状态的多个实例:

// In index.ts
export interface State {
    search: {
        main: searchReducer.State;
        other: searchReducer.State;
    };
}

还有一个参数化选择器来获得正确的选择器:

export const chooseSearchInstance = (instance: string): ((state: State) => searchReducer.State) => {
    switch(instance) {
        case 'MAIN': {
            return getMainSearchState;
        }
        case 'OTHER': {
            return getOtherSearchState;
        }
    }
};

问题

我正在尝试对搜索进行一些分页,因此我需要在 Effect 中使用上述选择器,以便知道它是否仍然是相同的搜索。但是,由于“withLatestFrom”只需要一个额外的 Observable 源而不是回调,我不确定如何在 Effect 中指定它?

@Effect()
public searchItems: Observable<Action> = this.actions.pipe(
    ofType<searchActions.PerformSearchAction>(searchActions.PERFORM_SEARCH),
    withLatestFrom(this.store.select(rootReducers.chooseSearch( action.payload.instance)),   // <-- Cannot do this since there is no access to action at this point.
    switchMap(([action, searchState] => (/* ... */))
);

我也尝试使用直接使用 this.store.select 的 mergeMap,但它导致了无限循环,因为这种效果最终会修改触发 mergeMap 中选择器的状态。

那么我将如何获得一个特定的搜索状态实例以用于此效果? (如果有更好的方法来表示相同类型状态的不同实例,我想我也会接受这样的回答,即整个实例的想法是错误的)。

【问题讨论】:

    标签: angular ngrx ngrx-effects


    【解决方案1】:

    我在尝试访问 withLatestFrom 中的操作时遇到了完全相同的问题,这就是我解决它的方法:

    // Same as withLatestFrom but used mergeMap/forkJoin because of use of action.payload
    mergeMap((action) => forkJoin(
      of(action),
      this.store.pipe(select(rootReducers.chooseSearch(action.payload.instance)), take(1)),
    )),
    switchMap([action, searchState] => (/* ... */))
    

    注意take(1) 的使用,否则代码会挂在我的经验中,它只是从参数化选择器中获取值。没有它它会挂起,因为我认为 forkJoin 等待所有 Observable 完成,而 take(1) 进行一次发射然后完成。

    【讨论】:

    • 我似乎不需要 forkJoin,而是在 select 的管道内做了一个内部 map() 并将所有内容作为数组返回。我认为最主要的是使用take(1),事后看来这是完全合理的。谢谢。
    • 听起来是一个很好的解决方案,如果您可以添加自己的答案来展示您所做的事情会很好,这样我就可以从中学习:) 很高兴它有帮助
    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-04-21
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多