Sub topic 11
Adding request timeouts
This chapter assumes you can write a service with HttpClient, use catchError and retry, and register a functional interceptor with withInterceptors. If any of these are unfamiliar, review the earlier chapters first.
Why a timeout is needed
A request can fail without ever producing an error. If the server accepts a connection and then stalls, the Observable stays open. The user sees a spinner, and a retry operator never runs because nothing has failed. A timeout turns "no answer" into an error that your existing handling can react to.
HttpClient has no timeout option. Browsers apply their own limits, which are long and not under your control. You add the limit yourself with the RxJS timeout operator.
The timeout operator
timeout errors if the source does not emit within the given time. When it errors, it unsubscribes from the source. For HttpClient, unsubscribing cancels the underlying request in the browser.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, timeout } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ReportService {
private http = inject(HttpClient);
getReport(): Observable<string> {
return this.http
.get('/api/report', { responseType: 'text' })
.pipe(timeout(5000));
}
}If no response arrives within 5000 ms, the Observable errors and the request is cancelled.
The error is a TimeoutError, imported from rxjs. It is not an HttpErrorResponse, and it has no status property. Code that reads error.status without checking the type will misreport it.
import { catchError, throwError, TimeoutError } from 'rxjs';
// Inside a pipe(...) after timeout():
catchError((error: unknown) => {
if (error instanceof TimeoutError) {
return throwError(() => new Error('The server took too long to respond.'));
}
return throwError(() => error);
})Applying a timeout in an interceptor
Setting timeout in every service is repetitive. Put it in an interceptor instead.
import { HttpInterceptorFn } from '@angular/common/http';
import { timeout } from 'rxjs';
export const timeoutInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(timeout(10_000));Register it together with the retry interceptor from the previous chapter:
provideHttpClient(withInterceptors([retryInterceptor, timeoutInterceptor]))Where the timeout sits relative to retry
The order of the interceptors decides what the limit means. The first interceptor in the array is the outermost.
With [retryInterceptor, timeoutInterceptor], each attempt gets its own 10-second limit. Three retries could take more than 40 seconds in total. If you want one limit for the whole operation, reverse the order so the timeout wraps the retries.
Retrying timeouts
The retry interceptor you built earlier rethrows anything that is not an HttpErrorResponse. A TimeoutError therefore passes straight through without a retry. For GET requests a timeout is often transient, so you may want to retry it. Change the check in the delay function:
if (
!(error instanceof TimeoutError) &&
(!(error instanceof HttpErrorResponse) || !RETRYABLE_STATUSES.has(error.status))
) {
return throwError(() => error);
}
return timer(2 ** (retryCount - 1) * 500);Import TimeoutError from rxjs.
Choosing a value
- Pick a limit above your normal slow responses, not above the average.
- Allow longer for uploads and report endpoints.
timeoutalso errors when no event arrives within the limit. If you usereportProgressandobserve: 'events', each progress event counts as an emission. - Skip the interceptor default for long-lived streams, such as server-sent events. Use the per-service form there instead.
Exercise
You register withInterceptors([timeoutInterceptor, retryInterceptor]), with a 10-second timeout and 3 retries. Does the 10-second limit apply to each attempt or to the whole operation, and what error does catchError receive?
Show answer
The limit applies to the whole operation, because the first interceptor listed is the outermost, so the timeout wraps the retries. When it fires, catchError receives a TimeoutError from rxjs, not an HttpErrorResponse, so check it with instanceof TimeoutError.