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

Angular中如何监听所有API响应并处理超时无返回的问题

实现方案

核心思路

  • 基于Angular原生HttpInterceptor全局拦截所有HttpClient发起的API请求,无需修改现有业务接口代码
  • 借助RxJS的timeout操作符统一设置请求超时阈值,超时后触发自定义的登出/刷新逻辑
  • 3分钟超时对应阈值为180000毫秒

步骤1:实现全局超时拦截器

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { timeout, catchError } from 'rxjs/operators';
import { Router } from '@angular/router'; // 用于跳转到登录页

@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
  // 超时阈值:3分钟 = 3 * 60 * 1000 = 180000毫秒
  private readonly TIMEOUT_THRESHOLD = 180000;

  constructor(private router: Router) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      // 设置超时时间
      timeout(this.TIMEOUT_THRESHOLD),
      catchError((error) => {
        // 判断是否为超时错误
        if (error.name === 'TimeoutError') {
          // 执行自定义逻辑,二选一即可
          // 方案1:退出登录,清除本地存储的token等信息,跳转到登录页
          localStorage.removeItem('auth_token');
          this.router.navigate(['/login']);
          
          // 方案2:直接刷新应用
          // window.location.reload();
        }
        // 抛出错误给业务层后续处理
        return throwError(() => error);
      })
    );
  }
}

步骤2:注册拦截器

在根模块AppModule的providers数组中添加拦截器配置:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TimeoutInterceptor } from './timeout.interceptor';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TimeoutInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

可选优化

  • 针对大文件上传、长连接等特殊接口,可在拦截器中添加白名单逻辑,跳过全局超时限制:
// 示例:跳过上传接口的超时校验
const whiteList = ['/api/upload', '/api/long-polling'];
if (whiteList.some(url => request.url.includes(url))) {
  return next.handle(request);
}
  • 可根据业务需要调整超时阈值,或添加超时提示弹窗提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:54:08