Angular Interceptors: Handling HTTP Requests and Responses

Angular Interceptors: Handling HTTP Requests and Responses


Introduction

Angular Interceptors are a powerful feature that allow you to intercept outgoing HTTP requests and incoming HTTP responses. They provide a way to pre-process or post-process HTTP requests and responses before they are sent to the server or delivered to the application. This can be useful for tasks such as adding authentication tokens to requests, logging requests and responses, or transforming data.

Setting Up Interceptors

To create an interceptor in Angular, you need to implement the HttpInterceptor interface. This interface defines a single intercept method that takes an HttpRequest object and a HttpHandler object as parameters. Inside the intercept method, you can modify the request or response as needed.

Interceptors are registered in the Angular application using the HTTP_INTERCEPTORS multi-provider. You can register interceptors globally in the app module or locally in a specific component.

Interceptor Functions

In the intercept method of an interceptor, you can perform various tasks on the HTTP request or response. For example, you can add headers to the request, modify the request body, or log the request. Here's an example of adding an authentication token to a request:

typescript

@Injectable()

export class AuthInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authToken = 'your-auth-token';

    const authRequest = request.clone({

      setHeaders: {

        Authorization: `Bearer ${authToken}`

      }

    });

    return next.handle(authRequest);

  }

}

Handling Responses

Interceptors can also be used to intercept HTTP responses. You can modify the response data or handle errors in the response. For example, you can log the response or transform the response data before it is delivered to the application. Here's an example of logging the response:

typescript

@Injectable()

export class LoggingInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(

      tap(event => {

        if (event instanceof HttpResponse) {

          console.log('Response received:', event);

        }

      })

    );

  }

}

Multiple Interceptors

Angular allows you to use multiple interceptors in your application. When multiple interceptors are used, they are executed in the order in which they are provided. This means that the output of one interceptor becomes the input of the next interceptor. This allows you to modularize your interceptors and keep them focused on specific tasks.

Real-World Example

To illustrate the use of interceptors in a real-world scenario, let's consider an example where you want to add a timestamp to all outgoing requests and log all incoming responses. You can achieve this by creating two interceptors: one for adding the timestamp and another for logging the responses.

typescript

@Injectable()

export class TimestampInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const timestampRequest = request.clone({

      setParams: {

        timestamp: new Date().getTime().toString()

      }

    });

    return next.handle(timestampRequest);

  }

}

@Injectable()

export class LoggingInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(

      tap(event => {

        if (event instanceof HttpResponse) {

          console.log('Response received:', event);

        }

      })

    );

  }

}

Conclusion

Angular Interceptors are a powerful tool for handling HTTP requests and responses in your Angular applications. They allow you to pre-process or post-process HTTP requests and responses, which can help you add authentication, logging, error handling, and other features to your application. By using interceptors, you can write cleaner and more maintainable code.

Previous Next

Start Your Data Journey Today With MSAInfotech

Take the first step towards data-led growth by partnering with MSA Infotech. Whether you seek tailored solutions or expert consultation, we are here to help you harness the power of data for your business. Contact us today and let’s embark on this transformative data adventure together. Get a free consultation today!

We utilize data to transform ourselves, our clients, and the world.

Partnership with leading data platforms and certified talents

FAQ Robot

How Can We Help?

Captcha

MSA Infotech