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次。你可以根据需要自定义重试次数和处理逻辑。

相关内容

热门资讯

目前!德普之星怎么开辅助,微信... 目前!德普之星怎么开辅助,微信小程序游戏破解微乐辅助,详细透视(的确有挂)-哔哩哔哩一、德普之星怎么...
脚本详细!wepoker免费脚... 脚本详细!wepoker免费脚本咨询,we poker插件(透视)其实有器(哔哩哔哩)小薇(辅助器软...
透视脚本!hh poker软件... 透视脚本!hh poker软件,淘宝的微乐辅助是真的吗,详细脚本(有挂秘籍)-哔哩哔哩1、下载好hh...
透视解密!wepoker免费透... 透视解密!wepoker免费透视脚本,wepoker辅助是真的假的(透视)真是存在有脚本(哔哩哔哩)...
出乎意料的是!wepoker可... 出乎意料的是!wepoker可以透视码,微乐如何自己建脚本,解迷透视(有挂解惑)-哔哩哔哩1、这是跨...
透视专业!wpk透视是真的假的... 透视专业!wpk透视是真的假的,wpk辅助软件(透视)一贯有插件(哔哩哔哩)能透视中分为三种模型:模...
透视好友!wejoker辅助软... 透视好友!wejoker辅助软件价格,手机微乐小程序自建房透视免费,解谜透视(有挂存在)-哔哩哔哩1...
透视透视!德普之星辅助器怎么用... 透视透视!德普之星辅助器怎么用,德普软件(透视)都是真的有教程(哔哩哔哩)辅助器是一种具有地方特色的...
透视好友!wepoker好友局... 透视好友!wepoker好友局透视,微信卡五星小程序辅助,详细透视(新版有挂)-哔哩哔哩1、每一步都...
脚本教你!德普之星透视,德普之... 脚本教你!德普之星透视,德普之星有透视辅助吗(透视)其实是有app(哔哩哔哩);1、全新机制【ai辅...