0
0
AngularHow-ToBeginner · 3 min read

How to Use HTTP Interceptor in Angular: Simple Guide

In Angular, you use an HTTP Interceptor by creating a class that implements HttpInterceptor interface and registering it in the providers array with HTTP_INTERCEPTORS. This lets you modify HTTP requests or responses globally before they reach your components.
📐

Syntax

An HTTP interceptor in Angular is a class that implements the HttpInterceptor interface. It must have an intercept(req, next) method that receives the outgoing request and a handler to forward the request.

You register the interceptor in your module's providers array using HTTP_INTERCEPTORS with multi: true to allow multiple interceptors.

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Modify request here
    const modifiedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
    return next.handle(modifiedReq);
  }
}

// In your module providers array
import { HTTP_INTERCEPTORS } from '@angular/common/http';

providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]
💻

Example

This example shows an interceptor that adds a custom header to every HTTP request and logs the request URL.

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

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('HTTP Request URL:', req.url);
    const clonedRequest = req.clone({
      headers: req.headers.set('X-Custom-Header', 'MyHeaderValue')
    });
    return next.handle(clonedRequest);
  }
}

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Output
Console output when making an HTTP request: HTTP Request URL: https://api.example.com/data
⚠️

Common Pitfalls

  • Not adding multi: true in the provider causes your interceptor to replace others, breaking HTTP handling.
  • Forgetting to clone the request before modifying it leads to errors because requests are immutable.
  • Not returning next.handle() or returning the wrong observable breaks the HTTP flow.
  • Placing interceptor registration outside the root or feature module can cause it not to apply.
typescript
/* Wrong: Missing multi: true */
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor }
]

/* Right: Include multi: true */
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]

/* Wrong: Modifying request without clone */
intercept(req, next) {
  // req.headers.set('Authorization', 'token'); // Error: immutable
  return next.handle(req);
}

/* Right: Clone before modifying */
intercept(req, next) {
  const cloned = req.clone({ headers: req.headers.set('Authorization', 'token') });
  return next.handle(cloned);
}
📊

Quick Reference

  • Implement HttpInterceptor interface.
  • Override intercept(req, next) method.
  • Clone requests before modifying.
  • Register interceptor with HTTP_INTERCEPTORS and multi: true.
  • Return next.handle(modifiedReq) observable.

Key Takeaways

Always implement the HttpInterceptor interface and override intercept method.
Clone the HttpRequest before modifying it to avoid immutability errors.
Register your interceptor in providers with multi: true to allow multiple interceptors.
Return next.handle() with the modified request to continue the HTTP flow.
Use interceptors to add headers, log requests, or handle errors globally.