Angular FAQ: Top Questions
41. What are Angular interceptors and how are they used?
HTTP Interceptors in Angular allow you to intercept and manipulate HTTP requests and responses globally. They are implemented by providing a class that implements the HttpInterceptor
interface.
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const cloned = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
return next.handle(cloned);
}
}
Register in providers
using HTTP_INTERCEPTORS
.