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

相关内容

热门资讯

据相关数据显示!四川游戏家园破... 据相关数据显示!四川游戏家园破解版,雀神山庄麻将辅助器,窍门教程(有挂详细)-哔哩哔哩1、四川游戏家...
事发当天!aa poker辅助... 事发当天!aa poker辅助包,we-poker正规吗(透视)解密教程(有挂规律)-哔哩哔哩1、每...
不少玩家反映!决战卡五星开挂方... 不少玩家反映!决战卡五星开挂方法,hhpoker一直输有挂吗,绝活教程(有挂方法)-哔哩哔哩1、许多...
推出新举措!pokemmo脚本... 推出新举措!pokemmo脚本辅助器下载,hhpoker是真的假的(透视)关于教程(有挂总结)-哔哩...
针对!新鸿狐辅助软件是真的吗,... 针对!新鸿狐辅助软件是真的吗,随意玩辅助软件,积累教程(揭秘有挂)-哔哩哔哩新鸿狐辅助软件是真的吗是...
透视最新!wepoker买脚本... 透视最新!wepoker买脚本靠谱吗,wepoker怎么买辅助(透视)普及教程(有挂头条)-哔哩哔哩...
于此同时!we-poker软件... 于此同时!we-poker软件,wpk俱乐部是真的吗(透视)总结教程(有挂分析)-哔哩哔哩wpk俱乐...
目前!越乡游义乌透视下载安卓,... 目前!越乡游义乌透视下载安卓,wepoker辅助分析器,经验教程(有挂神器)-哔哩哔哩1、超多福利:...
网友热议!德州局HHpoker... 网友热议!德州局HHpoker透视脚本,epoker透视(透视)专业教程(有挂总结)-哔哩哔哩德州局...
目前!小闲辅助软件,火神大厅科... 目前!小闲辅助软件,火神大厅科技,步骤教程(有挂存在)-哔哩哔哩1、游戏颠覆性的策略玩法,独创攻略技...