Intercepting HTTP Requests / Responses in Angular

Angular’s HttpInterceptor is a powerful feature that allows developers to intercept HTTP requests and responses in their Angular applications. This feature provides a way to modify HTTP requests and responses before they are sent or received. In this blog post, we’ll discuss what HttpInterceptor is, how to use it, and some best practices to follow.

What is HttpInterceptor?

HttpInterceptor is an Angular feature that allows you to intercept HTTP requests and responses in your application. It provides a way to modify requests and responses before they are sent or received. You can use HttpInterceptor to add headers, modify URLs, add authentication tokens, or handle errors.

Example #1: Intercept Request

To use HttpInterceptor, you need to create a class that implements the HttpInterceptor interface. This class should have a method called “intercept” that takes two parameters: the request and the next object. The request object represents the HTTP request, and the next object represents the next interceptor in the chain. The intercept method should return an Observable of the HTTP response.

Here’s an example of how to intercept a request and add an additional parameter:

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

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  // Intercept the general HTTP Call
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // This is executed before the Request is sent
    const newReq = req.clone({
      params: req.params.set('additionalParam', 'value')
    });
    
    // This aktually sends out the Request
    return next.handle(newReq);
  }
}
TypeScript

In this example, we’re intercepting the HTTP request and cloning it with an additional parameter.

Example #2: Intercept Response

Here’s an example of how to intercept a response:

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

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  // Intercept the general HTTP Call
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Send out the Request and handle the Response
    return next.handle(req).pipe(
      // This is executed as soon as the Response is received
      tap((event) => {
        if (event instanceof HttpResponse) {
          console.log('Response:', event);
        }
      })
    );
  }
}
TypeScript

In this example, we’re intercepting the HTTP response and logging it to the console.

Best Practices with HTTPInterceptor

Best Practices Here are some best practices to follow when using HttpInterceptor:

  1. Use HttpInterceptor to add headers, modify URLs, add authentication tokens, or handle errors.
  2. Avoid modifying the request or response in place. Instead, use the clone method to create a new request or response.
  3. Don’t use HttpInterceptor for caching or performance optimizations.
  4. Use HttpInterceptor sparingly, as too many interceptors can negatively impact performance.

Conclusion

Conclusion HttpInterceptor is a powerful feature in Angular that allows developers to intercept HTTP requests and responses in their applications. By using HttpInterceptor, developers can add headers, modify URLs, add authentication tokens, or handle errors. When using HttpInterceptor, it’s important to follow best practices, such as avoiding modifying requests or responses in place and using it sparingly.

By following these best practices, you can ensure that your application runs smoothly and efficiently while taking advantage of the full capabilities of Angular’s HttpInterceptor feature.

Leave a Reply