Roadmap › Angular (2 → 21) › Module: Services, DI and HTTP
Lessons in this course (16)
7. HttpClient, interceptors and error handling
Intermediate★ Must knowLesson 7 of 16
ts
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),
],
};
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
retry({ count: 2, delay: 500 }), // only for idempotent GETs in practice
catchError((err: HttpErrorResponse) => {
if (err.status === 401) inject(Router).navigate(["/login"]);
return throwError(() => err);
}),
);
// In a service
getOrder(id: number) {
return this.http.get<Order>(`/api/orders/${id}`, { params: { include: "lines" } });
}HttpClient returns cold observables — nothing happens until you subscribe (or use the async pipe / toSignal). Newer: httpResource() (signal-based HTTP resource, v19.2+).