What Is Interceptor In Angular And Use Cases Of Interceptor

In Angular, an interceptor is a middleware service that can intercept HTTP requests and responses from the application to the server. The interceptor can modify the requests or responses, add headers or tokens, handle errors, or perform any other necessary actions.

Interceptors are defined as services in Angular, and they can be added to the application by providing them in the HTTP_INTERCEPTORS multi-provider token.

Here's an example of an interceptor that adds an authorization token to every outgoing HTTP request:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const token = localStorage.getItem('auth_token');
    if (token) {
      const authRequest = request.clone({
        headers: request.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(authRequest);
    }
    return next.handle(request);
  }
}

In this example, the AuthInterceptor class implements the HttpInterceptor interface and provides the intercept() method. The intercept() method receives the incoming request and the HttpHandler object that allows us to pass the request to the next interceptor or the final HTTP handler.

The method first checks if an authorization token is present in the local storage. If the token is present, the method creates a new request with an additional Authorization header that includes the token. If the token is absent, the method passes the original request to the next handler.

To use this interceptor in your application, you need to provide it in the HTTP_INTERCEPTORS multi-provider token. Here's an example of how to do this:

import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
export class AppModule { }

In this example, the AuthInterceptor is provided in the HTTP_INTERCEPTORS token as a multi-provider, which means that it can be combined with other interceptors if needed.

Interceptors in Angular have several use cases:

  1. Authentication and authorization: You can use an interceptor to add authentication tokens or authorization headers to outgoing requests. This helps ensure that only authorized users can access protected resources.

  2. Error handling: You can use an interceptor to handle errors that occur during HTTP requests. This can be useful for handling network, timeouts, or server-side errors.

  3. Caching: You can use an interceptor to cache responses from the server, which can improve the performance of your application.

  4. Logging: You can use an interceptor to log HTTP requests and responses. This can be useful for debugging and monitoring your application's performance.

  5. Transformation of requests and responses: You can use an interceptor to modify the request or response data. This can be useful for adding or removing data or transforming data to match the format your application expects.

Overall, interceptors are a powerful feature of Angular that can help you improve your application's performance, security, and reliability. By using interceptors, you can centralize common functionality that needs to be applied to all HTTP requests and keep your code clean and modular.

Interceptors were introduced in Angular version 4.3.0 and are available in all subsequent versions. So, if you use Angular 4.3.0 or later, you can take advantage of the interceptor feature.

Note that interceptors are part of the @angular/common/http module, so you must import this module into your application to use interceptors. If you are using an earlier version of Angular that does not support interceptors, you can consider upgrading your application to a newer version of Angular to take advantage of this feature.

I hope this helps. If this helps you, then share it with others.

Sharing is caring! :)


Similar Articles