How can I use interceptor for an entire application?

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.

@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

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }],
bootstrap: [AppComponent],
})
export class AppModule {}

August 11, 2022
287