In Angular, an interceptor is a service that allows you to intercept and modify HTTP requests and responses globally before they are sent or received by the application. Interceptors are part of Angular's HttpClient
module and can be used for various purposes, such as adding authentication tokens, logging, error handling, or modifying request and response objects.
How Interceptors Work
Interceptors implement the HttpInterceptor
interface and can handle HTTP requests and responses by chaining them. They provide a powerful way to centralize and decouple common logic from the individual service calls.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth token from the service
const authToken = this.authService.getAuthToken();
// Clone the request and set the new header in one step
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
// Send the newly created request
return next.handle(authReq);
}
}