🅰️ Angular Q49 / 125

What is HttpInterceptor?

AI-Powered Answer ✓ Answered

Angular's `HttpInterceptor` provides a way to intercept HTTP requests and responses to modify them or handle them programmatically. It's a powerful mechanism for managing cross-cutting concerns in your application's HTTP communication.

What is an HttpInterceptor?

An HttpInterceptor is a service that implements the HttpInterceptor interface. It sits between your application and the backend, allowing you to examine and modify outgoing HttpRequests and incoming HttpResponses. This enables a clean separation of concerns for tasks like authentication, logging, or error handling.

Why use HttpInterceptors?

Interceptors are ideal for applying global transformations or handling common tasks across all HTTP requests and responses without modifying individual service calls. They help keep your components and services focused on their primary responsibilities.

  • Authentication: Automatically adding authorization tokens to outgoing requests.
  • Logging: Centralizing request and response logging for debugging or analytics.
  • Error Handling: Implementing global error handling strategies, such as showing notifications or retrying failed requests.
  • Caching: Developing custom caching mechanisms for HTTP responses.
  • Modifying Headers: Adding or modifying common headers (e.g., Content-Type, Accept-Language).
  • Loading Indicators: Managing global loading spinners or progress bars for active HTTP requests.

How HttpInterceptors Work

When you make an HTTP request using Angular's HttpClient, the request passes through a chain of registered interceptors. Each interceptor's intercept method gets called, allowing it to inspect, modify, or even stop the request. The request then proceeds to the next interceptor in the chain or ultimately to the backend. The response follows the reverse path back through the interceptors, allowing for similar manipulation.

Creating an HttpInterceptor

1. Implement the HttpInterceptor Interface

First, create a service that implements the HttpInterceptor interface and its intercept method. The intercept method receives the HttpRequest and HttpHandler.

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request and add new header
    const authReq = request.clone({
      headers: request.headers.set('Authorization', 'Bearer my-token')
    });
    // Pass the cloned request to the next handler
    return next.handle(authReq);
  }
}

2. Register the Interceptor

Interceptors must be provided as part of the HTTP_INTERCEPTORS multi-provider token in your Angular module (typically AppModule). The multi: true option is crucial as it allows you to register multiple interceptors.

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor'; // Import your interceptor

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule // Essential for HTTP services
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true // Essential for multiple interceptors
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Interceptor Flow and Order of Execution

Interceptors are executed in the order they are provided in the providers array. For outgoing requests, the first registered interceptor processes the request first. For incoming responses, the last registered interceptor processes the response first, creating a stack-like behavior. This order is important when multiple interceptors modify the same request or response properties.

Common Interceptor Scenarios

ScenarioDescriptionExample Action
Add Auth TokenAttaching authentication tokens (e.g., JWT) to outgoing requests.Clone request, add `Authorization` header before `next.handle()`.
Error HandlingCentralizing error management and displaying user-friendly messages for HTTP failures.Use `catchError` operator on the `next.handle()` observable, perform action, then rethrow.
Loading SpinnerManaging global loading indicators to show network activity.Increment a counter before `next.handle()`, decrement in `finally` block of the observable.
API VersioningDynamically adding an API version to all request URLs.Clone request, modify `url` property to include version string.
Request/Response LoggingLogging details of HTTP requests and responses for debugging purposes.Log request before `next.handle()`, log response details in `tap` operator on the observable.