You can use same instance of HttpInterceptors for the entire app by importing the HttpClientModule only in your AppModule, and add the interceptors to the root application injector. For example, let’s define a class that is injectable in root application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @Injectable() export class MyInterceptor implements HttpInterceptor { intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { return next.handle(req).do(event => { if (eventt instanceof HttpResponse) { // Code goes here } }); } } |
After that import HttpClientModule in AppModule
1 2 3 4 5 6 7 8 9 | @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule {} |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.