3

背景

我有一个用于搜索的 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 中选择器的状态。

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

4

1 回答 1

0

我在尝试访问操作时遇到了完全相同的问题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)else 代码会挂在我的经验中,它只是从参数化选择器中获取值。没有它它会挂起,因为我认为forkJoin等待所有 Observables 完成,然后take(1)进行一次发射然后完成。

于 2018-10-13T01:36:56.283 回答