What is Angular interceptor?
Answer
An HTTP interceptor intercepts all outgoing HTTP requests and incoming responses in Angular, allowing you to transform or handle them in a centralized location. Common uses: adding auth headers, logging, error handling, caching, request transformation. Creating an interceptor (class-based): @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = this.authService.getToken(); if (token) { req = req.clone({ headers: req.headers.set("Authorization", "Bearer " + token) }); } return next.handle(req); } }. Key points: (1) HttpRequest is immutable — clone with modifications; (2) Must call next.handle(req) to pass to the next interceptor or to the server; (3) Return value is an Observable of HttpEvents. Registering: in AppModule providers: { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }. The multi: true adds to an array of interceptors (not replacing). Multiple interceptors form a chain — execution order is the registration order for request, reverse for response. Functional interceptors (Angular 15+): export const authInterceptor: HttpInterceptorFn = (req, next) => { return next(req.clone({ headers: req.headers.set("Authorization", "Bearer " + token) })); };. Register: provideHttpClient(withInterceptors([authInterceptor])).