InterviewHubPRO
Section Overview
Q176

Question 176 of 283

Part 7: Change Detection, Security (XSS/Sanitizer) & Interceptors (151 - 176)

62%
Angular & Signals (283 Qs)•Part 7: Change Detection, Security (XSS/Sanitizer) & Interceptors (151 - 176)

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.

javascript
@Injectable()
export class MyInterceptor implements HttpInterceptor {
 intercept(
   req: HttpRequest<any>,
   next: HttpHandler
 ): Observable<HttpEvent<any>> {

   return next.handle(req).do(event => {
     if (event instanceof HttpResponse) {
          // Code goes here
     }
   });

 }
}

After that import HttpClientModule in AppModule

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