Understanding HTTP Interceptors in Angular

Understanding HTTP Interceptors in Angular

Understanding HTTP Interceptors in Angular

Understanding HTTP Interceptors in Angular


What is an HTTP Interceptor?


An HTTP Interceptor in Angular is a class that implements the HttpInterceptor interface. It allows you to intercept and modify HTTP requests or responses before they are sent to the server or after they are received. This feature is particularly useful for adding common functionality to multiple HTTP requests, such as setting authentication tokens, handling errors globally, or logging request details.


Key Use Cases for HTTP Interceptors:

  1. Adding Authentication Tokens:
  • Automatically attach a JWT (JSON Web Token) or any other authentication token to the headers of outgoing requests.
  1. Global Error Handling:
  • Capture and handle errors across all HTTP requests in a centralized manner.
  1. Logging Requests and Responses:
  • Log request and response details for debugging or auditing purposes.
  1. Modifying Request and Response Data:
  • Transform the data being sent to the server or received from the server.


How to Create an HTTP Interceptor in Angular

  1. Create the Interceptor Service: First, you need to generate a new service in your Angular project that will act as the interceptor.
bash
Copy code
ng generate service interceptors/auth
  1. This command will create a new service file (auth.service.ts) inside the interceptors folder.
  2. Implement the HttpInterceptor Interface: Open the newly created service file and implement the HttpInterceptor interface. This interface requires you to define the intercept method, which takes an HttpRequest and an HttpHandler as arguments.
typescript
Copy code
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
  
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({
      headers: req.headers.set('Authorization', `Bearer YOUR_TOKEN_HERE`)
    });

    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
  }
}
  1. In this example, the interceptor adds an Authorization header to each outgoing request.
  2. Provide the Interceptor in the Module: To use the interceptor, you need to provide it in your Angular module (app.module.ts).
typescript
Copy code
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptorService } from './interceptors/auth.service';

@NgModule({
  declarations: [
    // Your components
  ],
  imports: [
    HttpClientModule,
    // Other modules
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptorService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. The multi: true option allows Angular to use multiple interceptors if needed.

Best Practices for Using HTTP Interceptors

  • Chain Multiple Interceptors: You can chain multiple interceptors to handle different aspects of the request or response, such as authentication, logging, and error handling.
  • Avoid Side Effects: Ensure that interceptors do not cause unintended side effects, such as altering the original request data or introducing delays.
  • Error Handling: Use interceptors for global error handling, but avoid masking errors that should be exposed to the user or higher-level components.

Conclusion

HTTP Interceptors are a powerful tool in Angular that can help you manage HTTP requests and responses more efficiently. Whether you need to add authentication headers, log request details, or handle errors globally, interceptors provide a centralized and reusable solution. By implementing the practices outlined in this guide, you can streamline your HTTP communication and maintain a clean, maintainable codebase in your Angular applications.


Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts