我正在学习如何使用NGRX库将Redux架构集成到Angular应用中,并遇到了一个我想知道的有趣问题。我想知道当多个组件同时触发LoadApps操作时,如何防止对服务器的多个冗余API调用。
我有以下还原剂和作用:
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加载应用程序对象列表。如果我的角度应用程序中有两个同级组件,例如侧栏导航和顶部栏导航组件,每个组件都需要应用程序列表,则它们都将在其OnInit方法中触发LoadApps操作,结果是两个对服务器的完全相同的API调用。
如果效果在触发另一个api请求之前从状态中获取待处理的布尔值以确保它不是真的,那么在我看来,对效果的第二次调用可能已经开始运行,而待处理状态设为true之前。 / p>
NGRX是否为此提供某种机制?
答案 0 :(得分:4)
尝试使用exhaustMap
。
@Effect()
loadApps = this.actions.pipe(
ofType(AppsActionTypes.LoadApps),
exhaustMap(() => this.appService.getApps()),
map(res => [new LoadAppsSuccess(res)])
);
exhaustMap
将忽略所有传入事件,直到exhaustMap中的可观察到的事件完成为止。 https://www.learnrxjs.io/operators/transformation/exhaustmap.html