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?
Http
doesn't allow to have more than one custom implementation. But as @estus mentioned the Angular team has added a new HttpClient service recently (release 4.3) which supports multiple interceptors concept. You don't need to extend theHttpClient
as you do with the oldHttp
. You can provide an implementation forHTTP_INTERCEPTORS
instead which can be an array with the'multi: true'
option:Interceptors:
This server call will print both interceptors' log messages: