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

Angular rxResource遇非HTTP错误时陷入加载状态的解决方法

解决rxResource处理非HTTP错误(如CORS)时陷入加载状态的问题

问题原因

CORS、断网这类非HTTP错误,Angular HttpClient抛出的是ErrorEvent而非标准的HttpErrorResponse,这类错误对象没有status属性,导致你原代码中err.status == 0的判断无法命中,错误被直接重新抛出后,rxResource未能正确识别错误状态,持续维持加载状态。

解决方案

修改catchError的错误判断逻辑,覆盖网络类错误场景,确保错误被正确捕获并抛出,让rxResource能更新状态:

修改后的请求代码

tokenRequest = rxResource({
    params: () => this.loginRequested(),
    stream: ({params}) => {
      if (params == false) {
        return of(null);
      }
      return this.authService.requestLinkLogin()
        .pipe(
          catchError(err => {
            // 匹配CORS、断网等网络错误
            if (err instanceof ErrorEvent || !('status' in err)) {
              return throwError(() => new Error('网络错误:CORS或连接问题'));
            }
            // 处理HTTP状态码错误(4xx/5xx等)
            if (err.status >= 400) {
              return throwError(() => err);
            }
            // 其他未知错误重新抛出
            return throwError(() => err);
          })
        );
    }
  })

说明

  • 新增的err instanceof ErrorEvent判断会直接捕获CORS这类浏览器层面的网络错误;
  • !('status' in err)作为兜底,覆盖所有没有status属性的非HTTP错误;
  • 错误被正确抛出后,rxResource会自动将isLoading设为false,并把错误赋值给error(),UI就能正常显示错误区块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 19:02:31