You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+NgRx中HTTP请求超时未触发订阅回调方法问题

Angular + NgRx Effect 网络故障下finalize/error未触发问题

初始实现代码

@Effect()
customAction$ = this._actions$.pipe(
    ofType<CustomAction>(Actions.CustomAction),
    tap(() => console.log('Custom Action was triggered')),
    switchMap((res) => {
        console.log('before http request...');
        this.myservice.DoApiCall().pipe(finalize(() => {
            console.log('finalize triggered...');
        })).subscribe(resultInner => {
                console.log('next() trigerred...');
                // other logic ....
            },
            () => {
                console.log('error() triggered...');
            });
        return EMPTY;
    })
);

遇到的问题

触发CustomAction后,若出现网络故障导致HTTP请求无响应,订阅的error()回调和finalize()操作符内的代码都不会执行。原本预期finalize无论请求完成与否都会触发。

修改后的代码(仍偶发问题)

按照建议移除了内部订阅,直接返回HTTP请求的Observable,但网络故障时问题依旧偶现:

@Effect()
customAction$ = this._actions$.pipe(
    ofType<CustomAction>(Actions.CustomAction),
    tap(() => console.log('Custom Action was triggered')),
    switchMap((result) => {
        return this.myservice.DoApiCall().pipe(
            catchError((error) => {
                // console.log('error caught');
            }),
            finalize(() => {
                // console.log('finalize');
            })
        );
    })
);

说明与临时解决方案

  • 因需要在外部Observable再次触发时取消内部请求,所以倾向使用switchMap而非mergeMap,暂不考虑替换。
  • 临时解决方案:在HTTP请求的Observable中串联timer操作符设置30秒超时阈值,网络故障导致请求无响应时,30秒后catchError会被触发,以此绕过问题。

内容的提问来源于stack exchange,提问作者NickAth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:29:53