angular - 防止 NGRX 效应产生的冗余 API 调用

标签 angular redux rxjs ngrx

我正在学习如何使用 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/

相关文章:

Angular2 jwt 通过子模块中的拦截器进行身份验证

angular - 当 Font Awesome 带宽使用量超过我本月计划允许的 npm 带宽时,会发生什么?

javascript - react : What would be a recommended way to cache state of the app in the browser to minimize the amount of requests to the backend?

Angular 4 - 取消订阅的最佳方式

javascript - 如果没有匹配的累加器,RxJS 如何减少?

javascript - 推荐使用或不使用Subject

forms - 如何验证至少应选中一个复选框?

typescript - 将服务注入(inject)组件

javascript - 当其中一个字段是数组时如何更改状态对象?

javascript - 如何在React Redux中使用不同的参数调度相同的操作