An HttpInterceptor in Angular is used to modify outgoing HTTP requests before they are sent to the server. It is commonly used for adding authentication tokens, logging, or modifying headers.
Implementation Example: Adding an Authorization Header
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedReq = req.clone({
setHeaders: { Authorization: `Bearer your-token-here` }
});
return next.handle(modifiedReq);
}
}