What is interceptor in Angular and how to use?

An Interceptor in Angular is a powerful feature that can be used to pre-process or post-process HTTP requests and responses. An interceptor is a service that implements the HttpInterceptor interface and can be used to manipulate HTTP requests before they are sent to the server and HTTP responses before they are returned to the calling code.

Here’s an example of how to create an interceptor in Angular:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // manipulate the request before it is sent to the server
    const modifiedReq = req.clone({
      setHeaders: {
        'Content-Type': 'application/json'
      }
    });

    return next.handle(modifiedReq);
  }
}

In this example, the MyInterceptor service implements the HttpInterceptor interface and overrides its intercept method. The intercept method takes an HttpRequest object and an HttpHandler object as arguments and returns an Observable of HttpEvent objects.

In the intercept method, the req object is cloned, and the setHeaders property is set to include a Content-Type header with a value of application/json. Finally, the modified request is passed to the next.handle method, which sends the request to the server and returns an Observable of HttpEvent objects representing the response.

To use the interceptor, you must add it to the HTTP_INTERCEPTORS provider in your module’s providers array:

import { HTTP_INTERCEPTORS } from '@angular/common/http';

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

With this setup, any HTTP request sent using the Angular HttpClient module will be intercepted and processed by the MyInterceptor service before being sent to the server.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *