HttpClient and interceptors
Every serious front end spends most of its life talking to an API. Angular's
HttpClient is typed, cancellable, and interceptable — which is how auth,
retries and error handling stay out of your components.
Providing it
provideHttpClient( withFetch(), // fetch backend; needed for SSR withInterceptors([authInterceptor, errorInterceptor, retryInterceptor]), )
A typed API service
@Injectable({ providedIn: 'root' })
export class OrderApi {
private readonly http = inject(HttpClient);
private readonly base = '/api/orders';
page(filter: OrderFilter, page: number, size: number): Observable<Page<Order>> {
let params = new HttpParams()
.set('page', page)
.set('size', size);
if (filter.status) params = params.set('status', filter.status);
if (filter.query) params = params.set('q', filter.query);
return this.http.get<Page<Order>>(this.base, { params });
}
byId(id: number): Observable<Order> {
return this.http.get<Order>(`${this.base}/${id}`);
}
create(body: CreateOrderRequest): Observable<Order> {
return this.http.post<Order>(this.base, body);
}
cancel(id: number): Observable<void> {
return this.http.post<void>(`${this.base}/${id}/cancel`, {});
}
// read a response header — you must ask for the full response
createWithLocation(body: CreateOrderRequest): Observable<string> {
return this.http.post<Order>(this.base, body, { observe: 'response' })
.pipe(map(res => res.headers.get('Location') ?? ''));
}
export(filter: OrderFilter): Observable<Blob> {
return this.http.get(`${this.base}/export`, {
params: toParams(filter),
responseType: 'blob',
});
}
}
params.set(...) returns a new object. Writing
params.set('page', 1); on its own line silently does nothing — you must
reassign, as above.
Functional interceptors
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
const token = auth.currentToken();
// never attach the token to third-party hosts
if (!token || !req.url.startsWith('/api')) {
return next(req);
}
return next(req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
}));
};
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
const toast = inject(ToastService);
return next(req).pipe(
catchError((err: HttpErrorResponse) => {
switch (err.status) {
case 0:
toast.error('Network unavailable. Check your connection.');
break;
case 401:
auth.logout(); // token expired
break;
case 403:
toast.error('You do not have permission to do that.');
break;
case 409:
// let the component handle conflicts — it has the context
break;
case 500:
toast.error(`Something went wrong. Reference: ${err.error?.reference ?? '—'}`);
break;
}
return throwError(() => err); // always rethrow
}),
);
};
If you return of(null) instead of rethrowing, every caller sees a successful
empty response and renders an empty screen with no explanation. Handle the cross-cutting
part — a toast, a redirect — then rethrow so the component can still react.
Retry with backoff
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
// only idempotent methods may be retried safely
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(
retry({
count: 2,
delay: (error: HttpErrorResponse, retryCount) => {
// do not retry client errors — they will not become valid
if (error.status >= 400 && error.status < 500) {
return throwError(() => error);
}
const backoff = Math.pow(2, retryCount) * 300;
const jitter = Math.random() * 200;
return timer(backoff + jitter);
},
}),
);
};
Cancellation — the thing fetch makes hard and RxJS makes free
export class OrderSearchComponent {
private readonly api = inject(OrderApi);
readonly query = signal('');
readonly results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
filter(q => q.length === 0 || q.length >= 2),
// switchMap CANCELS the previous in-flight request
switchMap(q => q ? this.api.search(q) : of([])),
catchError(() => of([])),
),
{ initialValue: [] as Order[] },
);
}
Without switchMap, a slow response for "OR" can arrive after the fast response
for "ORD-104" and overwrite it. That out-of-order bug is subtle, intermittent, and
eliminated by one operator.
Loading and error state in the component
export class OrderListComponent {
private readonly api = inject(OrderApi);
readonly loading = signal(false);
readonly error = signal<string | null>(null);
readonly orders = signal<Order[]>([]);
load(): void {
this.loading.set(true);
this.error.set(null);
this.api.page(this.filter(), 0, 25)
.pipe(finalize(() => this.loading.set(false)))
.subscribe({
next: page => this.orders.set(page.content),
error: (e: HttpErrorResponse) =>
this.error.set(e.status === 0
? 'You appear to be offline.'
: 'Could not load orders. Try again.'),
});
}
}
Uploads with progress
upload(file: File): Observable<number> {
const form = new FormData();
form.append('file', file);
return this.http.post('/api/imports', form, {
reportProgress: true,
observe: 'events',
}).pipe(
filter(e => e.type === HttpEventType.UploadProgress),
map(e => Math.round(100 * e.loaded / (e.total ?? 1))),
);
}
Why must the retry interceptor skip POST requests?
If the server processed the request but the response was lost, retrying places a second
order. Retry GET, PUT and DELETE freely; for
POST, make the endpoint idempotent with a client-supplied key and let the
server deduplicate.