Angular 5拦截器-仅在第一个拦截器重试失败后才调用第二个拦截器 [英] Angular 5 Interceptor - Only call second interceptor after failed retry on first interceptor

查看:301
本文介绍了Angular 5拦截器-仅在第一个拦截器重试失败后才调用第二个拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个我有2个拦截器的angular 5应用程序:

I am building an angular 5 app where I have 2 interceptors:

  • 一个重试失败的504个请求
  • 另一个向用户显示有关失败请求的错误消息

我希望第二个拦截器仅在错误不是504或错误504且已被第一个拦截器重试时才被调用.

I want that the second interceptor only gets called when the error is not 504 or when it is 504 and has already been retried by the first interceptor.

我用两个拦截器创建了一个样本: https://stackblitz.com/edit/angular-interceptors-ckbvsb

I have created a sample with both interceptors: https://stackblitz.com/edit/angular-interceptors-ckbvsb

希望得到一些帮助!

谢谢

更新:

感谢大家的帮助!我最终像这样实现它:

Thanks everyone for your assistance! I have ended up implementing it like this:

@Injectable()
export class I1 implements HttpInterceptor {
 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 console.log('intercepted I1');

 return next.handle(req)
  .retryWhen(error => {
    return error
      .mergeMap((err, i) => {
        if (i > 0) return Observable.throw(err)
        if (err instanceof HttpErrorResponse && err.status === 504) { // timeout
          return Observable.of(err).delay(5000);
        } else {
          return Observable.throw({ error: 'No retry', cause: err })
        }
      })
  });
 }
}

推荐答案

问题是您提供两个拦截器的顺序.您要先提供I1,然后再提供I2.这意味着请求将流经I1→I2,但是响应将流经I2,然后才流经I1.因此,只需切换顺序:

Your issue is the order in which you provide the two interceptors. You are providing I1 first and then I2. This means that a request will flow through I1 → I2, but the response will flow through I2 and only then through I1. So just switch the order:

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    declarations: [AppComponent],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: I2,               // <-- I2 first
            multi: true
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: I1,               // <-- And only then I1
            multi: true
        }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

这篇关于Angular 5拦截器-仅在第一个拦截器重试失败后才调用第二个拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆