In Angular, an interceptor is a service that intercepts HTTP requests or responses before they reach the server or the component. Interceptors are part of Angular’s HttpClient
module and are commonly used for:
- Adding headers (e.g., authentication tokens)
- Logging requests/responses
- Handling errors globally
- Modifying requests or responses
How Interceptors Work
When you make an HTTP request using Angular’s HttpClient
, the request passes through all registered interceptors in the order they were provided. Similarly, the response goes back through them in reverse order.
Interceptors implement the HttpInterceptor
interface.
Basic Example: Adding an Authorization Token
1. Create an Interceptor
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add a new header
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer YOUR_TOKEN_HERE`
}
});
console.log('Intercepted request:', authReq);
return next.handle(authReq); // Forward the request
}
}
2. Provide the Interceptor in App Module
// app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true // Important: allows multiple interceptors
}
]
})
export class AppModule {}
3. Use HttpClient Normally
// example.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ExampleService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data');
}
}
- Every request sent via
HttpClient
now automatically includes the Authorization header.
✅ Key Points
- Interceptors do not modify the original request; they work on a cloned copy.
- You can have multiple interceptors; they are executed in the order provided.
- Interceptors are perfect for cross-cutting concerns like logging, error handling, or authentication.