Angular HTTP Interceptors
Tags: angular, webdev, javascript, frontend
Published: 2023-12-24 12:17:56

## Overview

- In this article, I will introduce you to `Angular HTTP Interceptors`. I hope it proves helpful for your future implementations. This crucial Angular feature boasts numerous use cases, and its implementation and maintenance are straightforward.


## Table of Contents

- [Introduction](#introduction)
- [What are Angular HTTP Interceptors](#what-are-angular-http-interceptors)
- [Use Cases](#use-cases)
- [How to Implement](#how-to-implement)

## What are Angular HTTP Interceptors

- Angular HTTP Interceptors are a powerful feature that enables developers to intercept and manipulate HTTP Requests and Responses globally within an Angular application. It acts as middleware, allowing interception at both the request and response levels.
  - Since interceptors are typically registered at the application level, they have a global scope and can be utilized to handle common tasks across different parts of your application.
  - Angular chains multiple interceptors together. Each interceptor in the chain can determine whether to pass the request to the next one or modify the request/response as necessary.

## Use Cases

- **Adding headers to requests (authentication tokens):**
  Interceptors enable the inclusion of headers in outgoing requests, such as authentication tokens for secure communication.

- **Logging HTTP activity for debugging and monitoring:**
  Utilize interceptors to log HTTP activity, facilitating debugging and monitoring processes within your application.

- **Implementing loading indicators or other UI-related tasks:**
  Angular HTTP Interceptors empower the implementation of loading indicators or other user interface-related tasks for a seamless user experience.

- **Handling errors globally:**
  Intercept and handle errors at a global level, ensuring consistent and centralized error management throughout your application.

- **Modifying request or response data:**
  Customize and modify request or response data as needed, offering high control over the communication process.

## How to Implement

Below is an example of an Angular HTTP Interceptor for handling loading indicators. The `LoadingInterceptor` intercepts HTTP requests, starting and stopping a global loading indicator.

```Typescript
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { GlobalLoadingService } from 'src/app/core/services/GlobalLoadingService/GlobalLoadingService.service';

@Injectable()
export class LoadingInterceptor implements HttpInterceptor {

  constructor(private globalLoadingService: GlobalLoadingService) { }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    this.globalLoadingService.startLoading();
    return next.handle(request).pipe(
      finalize(() => this.globalLoadingService.stopLoading())
    );
  }
}
```

**Defining HTTP Interceptor on AppModule**

```Typescript
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor },
  ],
})
export class AppModule { }
```


## Thanks for Reading!

- I hope you gained insights into upgrading your project's node version to achieve more: performance, security, maintainability, reliability, and more.
- Feel free to reach out if you have any questions, feedback, or suggestions. Your engagement is appreciated!
- You can find more about Angular Interceptors at [Angular docs](https://angular.io/docs).
- Examples related to this article can be found at: https://github.com/godinhojoao/angular-interceptors


## Contacts

- You can find this and more content on:
  - [GitHub](https://github.com/godinhojoao)
  - [LinkedIn](https://www.linkedin.com/in/joaogodinhoo/)