gpt4 book ai didi

angular - NGRX 从有效的参数化选择器获取状态

转载 作者:行者123 更新时间:2023-12-05 07:29:25 25 4
gpt4 key购买 nike

背景

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

那么我如何才能获得要在该 Effect 中使用的 Search State 的特定实例? (如果有更好的方法来表示同一类型状态的不同实例,我想我也会接受这样的答案:整个实例的想法是错误的)。

最佳答案

我在尝试访问 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 等待所有 Observables 完成,而 take(1) 进行一次发射然后完成。

关于angular - NGRX 从有效的参数化选择器获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com