What is the use of Interceptors in Angular

In Angular, interceptors are a powerful feature of the HTTP Client module that allow you to modify or manipulate HTTP requests and responses. They are typically used to handle common tasks like adding headers, logging, error handling, authentication, caching, and more. Interceptors act as middleware for HTTP requests made by your Angular application.

Key Uses of Interceptors in Angular

  1. Adding Headers or Tokens: Interceptors are often used to automatically attach headers or authentication tokens (like JWTs) to every HTTP request. This is particularly useful for ensuring that all outgoing requests have the necessary credentials to access protected resources.

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authToken = 'your-auth-token'; // Replace with actual token retrieval logic
        const clonedRequest = req.clone({
          headers: req.headers.set('Authorization', `Bearer ${authToken}`)
        });
        return next.handle(clonedRequest);
      }
    }
    
     
  2. Error Handling: Interceptors can catch errors from HTTP responses and handle them in a consistent way across your application. For example, you might want to log errors, display notifications, or redirect users to a login page if a 401 Unauthorized response is detected.

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
    import { Observable, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
          catchError((error: HttpErrorResponse) => {
            console.error('Error occurred:', error);
            // Handle error, e.g., show a notification
            return throwError(() => error);
          })
        );
      }
    }
    
     
  3. Logging Requests and Responses: Interceptors can log information about outgoing HTTP requests or incoming responses, which is useful for debugging and monitoring.

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    import { Observable, tap } from 'rxjs';
    
    @Injectable()
    export class LoggingInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('Request made to:', req.url);
        return next.handle(req).pipe(
          tap(event => {
            console.log('Response received from:', req.url, event);
          })
        );
      }
    }
    
     
  4. Caching: Interceptors can be used to implement client-side caching strategies by storing responses in a cache and serving cached responses instead of making new HTTP requests.

  5. Modifying Requests or Responses: You can modify the request or response data (like adding query parameters or transforming the response body) before it reaches the component or service making the request.

How to Use Interceptors in an Angular Application

  1. Create the Interceptor: Define the interceptor by implementing the HttpInterceptor interface.

  2. Register the Interceptor: Register the interceptor in the providers array of your Angular module, usually in app.module.ts:

    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    import { AuthInterceptor } from './path-to-auth-interceptor';
    import { ErrorInterceptor } from './path-to-error-interceptor';
    
    @NgModule({
      // ...
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
      ],
    })
    export class AppModule { }
    
     

    The multi: true flag is important because it tells Angular to keep the existing interceptors and add the new ones, rather than replacing them.

 

Benefits of Using Interceptors

  • Centralized Logic: Interceptors allow you to centralize logic that applies to all HTTP requests or responses, making the code cleaner and more maintainable.
  • Consistency: Ensures consistent behavior for all HTTP requests (like error handling, logging, and authorization).
  • Reusability: Easily reusable across multiple components and services.

 

Summary

Interceptors in Angular provide a mechanism to modify or handle HTTP requests and responses globally. They are a versatile tool that helps you implement cross-cutting concerns like authentication, logging, error handling, and caching efficiently.

Would you like more details on a specific use case of Angular interceptors, or perhaps a code example tailored to your project?