InterviewHubPRO
Section Overview
Q173

Question 173 of 283

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

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

What are Http Interceptors?

Http Interceptors are part of @angular/common/http, which inspect and transform HTTP requests from your application to the server and vice-versa on HTTP responses. These interceptors can perform a variety of implicit tasks, from authentication to logging.

The syntax of HttpInterceptor interface looks like as below,

javascript
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

You can use interceptors by declaring a service class that implements the intercept() method of the HttpInterceptor interface.

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

After that you can use it in your module,

javascript
@NgModule({
  ...
  providers: [
      {
          provide: HTTP_INTERCEPTORS,
          useClass: MyInterceptor,
          multi: true
      }
  ]
  ...
})
export class AppModule {}