我正在学习如何使用 NGRX 库将 Redux 架构集成到 Angular 应用程序中,并遇到了一个我想知道的有趣问题。我想知道当多个组件同时触发 LoadApps 操作时,如何防止对服务器的多个和冗余 API 调用。
我有以下 reducer 和效果:
export function appsReducer(state = initialState, action: AppsActions): AppsState {
switch (action.type) {
case AppsActionTypes.LoadApps:
return {
...state,
pending: true,
data: []
};
case AppsActionTypes.LoadAppsSuccess:
return {
...state,
pending: false,
data: action.payload
};
default:
return state;
}
}
@Effect()
loadApps = this.actions.pipe(
ofType(AppsActionTypes.LoadApps),
concatMap(() => this.appService.getApps().pipe(
switchMap((res: App[]) => {
return [new LoadAppsSuccess(res)];
})
))
);
从我的 API 加载应用程序对象列表。如果我的 angular 应用程序中有两个兄弟组件,例如侧栏导航和顶部栏导航组件,每个组件都需要应用程序列表,它们都会在它们的 OnInit 方法中触发 LoadApps 操作,从而导致两个对服务器的完全相同的 API 调用。
如果效果从状态获取挂起的 bool 值以确保在触发另一个 api 请求之前它不是真的,在我看来,在挂起设置为 true 之前,对效果的第二次调用可能已经开始运行。
NGRX 是否为此提供了某种机制?
最佳答案
尝试使用 exhaustMap
.
@Effect()
loadApps = this.actions.pipe(
ofType(AppsActionTypes.LoadApps),
exhaustMap(() => this.appService.getApps()),
map(res => [new LoadAppsSuccess(res)])
);
exhaustMap
将忽略任何传入事件,直到exhaustMap 中的observable 完成。 https://www.learnrxjs.io/operators/transformation/exhaustmap.html
关于angular - 防止 NGRX 效应产生的冗余 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440156/