withInterceptors is an Angular HTTP configuration function that registers functional interceptors in the interceptor pipeline. In a standalone application, provide it through provideHttpClient in app.config.ts. section 3.3.3
Use withInterceptors when configuring functional HTTP behavior, especially during migration:
- Create an HttpInterceptorFn that injects required services, clones the request when needed, and passes it to the next handler. section 3.3.3
- Register one or more functional interceptors with provideHttpClient(withInterceptors([...])). section 3.3.3
- Replace legacy HTTP_INTERCEPTORS registration progressively; use withInterceptorsFromDi temporarily when class-based interceptors must remain available. section 3.3.4
Adding an authentication header
An authInterceptor can inject AuthService, retrieve a token, clone each HttpRequest with an Authorization Bearer header, and call the next handler. Registering it in app.config.ts applies it to HTTP calls across the application. section 3.3.3
Listing 3.14 Authentication interceptor
import { HttpHandlerFn, HttpRequest, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
export const authInterceptor: HttpInterceptorFn = ( #1
req: HttpRequest<any>, #2
next: HttpHandlerFn, #3
) => {
const authService = inject(AuthService);
const token = authService.getToken();
const newReq = req.clone({setHeaders: {
'Authorization': `Bearer ${token}`, #4
}});
return next(newReq); #5
}
Inspect the complete functional authentication interceptor, including inject, request cloning, header creation, and handler delegation. section 3.3.3
Listing 3.15 Registering an interceptor
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(
withInterceptors([authInterceptor]),
),
],
};
Inspect the standalone app configuration that registers authInterceptor through provideHttpClient and withInterceptors. section 3.3.3
