Angular中的HttpInterceptor不会重试失败的请求。
创始人
2024-10-31 06:00:20
0

在Angular中,HttpInterceptor并不自动重试请求。但我们可以通过自定义一个HttpInterceptor来实现请求失败时的重试。下面是一个示例代码:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(request).pipe(
      retry(3), // 重试3次
      catchError((error: HttpErrorResponse) => {
        if (error.status === 0 || error.status === 500) {
          // 处理特定的错误状态码,如网络错误或服务器错误
          // 可以根据需要进行其他处理,比如显示错误消息等
          console.error('An error occurred:', error);
        }
        return throwError(error); // 抛出错误,以便后续的错误处理器处理
      })
    );
  }
}

要使用这个自定义的HttpInterceptor,我们需要在app.module.ts中提供它:

import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RetryInterceptor } from './retry.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: RetryInterceptor, multi: true }
  ]
})
export class AppModule { }

现在,每当请求失败时,HttpInterceptor会尝试重新发送请求,最多重试3次。你可以根据需要自定义重试次数和处理逻辑。

相关内容

热门资讯

辅助透视!wpk脚本是什么,w... 辅助透视!wpk脚本是什么,wepoker私人局透视插件,玩家教程(有挂黑科技)1、首先打开wpk脚...
透视好牌"wepok... 透视好牌"wepoker透视app下载"详细辅助辅助教程(辅助器下载软件);支持多人共享记分板与复盘...
透视挂!wepoker辅助下载... 透视挂!wepoker辅助下载,德州私人局脚本,可靠教程(有挂技巧)该软件可以轻松地帮助玩家将wep...
透视美元局"aapo... 透视美元局"aapoker免费透视脚本"详细辅助2025新版教程(辅助器方法);科技安装教程;136...
透视实锤!红龙poker透视工... 透视实锤!红龙poker透视工具,impoker辅助,新版2025教程(有挂细节)1、进入到红龙po...
透视肯定"wepok... 透视肯定"wepoker代打辅助机器人"详细辅助扑克教程(插件辅助技巧)是一款可以让一直输的玩家,快...
透视私人局!wpk透视脚本,a... 透视私人局!wpk透视脚本,aapoker透视脚本入口,wpk教程(有挂方法)1、aapoker透视...
透视脚本"来玩app... 透视脚本"来玩app 德州 辅助"详细辅助系统教程(钻石可以看底牌教程);亲真的是有正版授权,小编(...
透视模拟器!hhpoker透视... 透视模拟器!hhpoker透视脚本,哈糖大菠萝攻略,专业教程(有挂教程);1、hhpoker透视脚本...
透视科技"hhpok... 透视科技"hhpoker真的假的"详细辅助wpk教程(可以开辅助方法);《WPK辅助透视》‌:支持手...