Add multiple HTTP Interceptors to Angular Application

Viewed 47993

How to add multiple, independent HTTP interceptors to an Angular 4 application?

I tried to add them by extending the providers array with more than one interceptors. But only the last one is actually executed, Interceptor1 is ignored.

@NgModule({
  declarations: [ /* ... */ ],
  imports: [ /* ... */ HttpModule ],
  providers: [
    {
      provide: Http,
      useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
        new Interceptor1(xhrBackend, requestOptions),
      deps: [XHRBackend, RequestOptions],
    },
    {
      provide: Http,
      useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
        new Interceptor2(xhrBackend, requestOptions),
      deps: [XHRBackend, RequestOptions]
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

I could obviously combine them into a single Interceptor class and that should work. However, I would like to avoid that as these interceptors have completely different purposes (one for error handling, one to show a loading indicator).

So how can I add multiple interceptors?

1 Answers
Related