HttpClient and API Integration
Why this matters
Section titled “Why this matters”Almost every real application is mostly a client for someone else’s API, and the HTTP layer is where the least-fun problems live: race conditions between requests, error handling that swallows the useful information, auth tokens duplicated across forty call sites, requests that keep running after the user navigated away.
HttpClient solves most of that if you use it as intended. The intended shape is: thin API-client services, cross-cutting behaviour in interceptors, and cancellation you did not have to think about.
Terminology
Section titled “Terminology”HttpClient— the injectable service that issues requests.- Backend — the transport implementation.
fetchby default;XMLHttpRequestviawithXhr(). - Interceptor — middleware in the request/response chain.
HttpContext— a typed map carried on a request for interceptors, never sent to the server.HttpEvent— one of several events a request emits (sent, upload progress, response). Most code only sees the final response.- Cold observable — nothing happens until subscription.
HttpClientreturns these.
The mental model
Section titled “The mental model”An HttpClient observable is a blueprint for a request, not a request.
That one sentence explains most HttpClient behaviour:
- No subscription, no request.
this.http.get(url)on its own does nothing. - Two subscriptions, two requests. Each subscription is independent.
- Unsubscribing aborts the in-flight request. This is why the
AsyncPipecancels on navigation and whyswitchMapcancels superseded requests for free. - The observable completes after the response, so an un-torn-down subscription usually will not leak — but the callback can still run against a destroyed component, so tear it down anyway.
httpResource is the exception, and deliberately so: it initiates its request eagerly, because a signal has to have a value.
HttpClient is available for injection by default from Angular v21 onwards. You only call provideHttpClient when you need to configure a feature:
export const appConfig: ApplicationConfig = { providers: [ provideHttpClient( withInterceptors([authInterceptor, retryInterceptor, loadingInterceptor]), withXsrfConfiguration({ cookieName: 'CSRF-TOKEN', headerName: 'X-CSRF-TOKEN' }), ), ],};The features
Section titled “The features”| Feature | Purpose |
|---|---|
withInterceptors([...]) |
Functional interceptors — the recommended kind |
withInterceptorsFromDi() |
Legacy class-based interceptors |
withXsrfConfiguration({...}) |
Custom XSRF cookie/header names |
withNoXsrfProtection() |
Disable built-in XSRF handling |
withRequestsMadeViaParent() |
Add interceptors in a child injector, then pass up to the parent’s client |
withXhr() |
Use XMLHttpRequest instead of fetch |
withFetch() |
Deprecated — fetch is already the default backend |
withJsonpSupport() |
Deprecated — JSONP can cause XSS; use CORS |
Two of these carry warnings worth taking seriously.
withXhr() must not be used in SSR. XHR support on the server is deprecated with intent to remove in Angular 23. The underlying xhr2 library does not handle redirects safely: it can forward Authorization headers across cross-origin redirects, and it is vulnerable to denial of service through redirect loops. Use the default fetch backend on the server.
withJsonpSupport() is deprecated as of 22.1 because JSONP can cause XSS vulnerabilities — it executes the response as script by design. Use CORS.
withFetch() is deprecated simply because it is redundant: FetchBackend is already the default. Note the one real limitation of fetch — it does not produce upload progress events. If you need an upload progress bar, that is the case for withXhr() in the browser.
Making requests
Section titled “Making requests”@Service()export class OrderApiClient { private readonly http = inject(HttpClient);
list(status: string, page: number): Observable<Page<Order>> { return this.http.get<Page<Order>>('/api/orders', { params: new HttpParams().set('status', status).set('page', page), }); }
create(draft: OrderDraft): Observable<Order> { return this.http.post<Order>('/api/orders', draft); }
remove(id: string): Observable<void> { return this.http.delete<void>(`/api/orders/${id}`); }}Angular’s own best-practice guidance: wrap HTTP in reusable injectable services rather than calling HttpClient from components. A component that knows a URL is a component you cannot change the API under.
HttpParams and HttpHeaders are immutable — set and append return new instances. The classic bug:
const params = new HttpParams();params.set('page', 1); // discarded; params is still emptyconst ok = new HttpParams().set('page', 1); // correctUseful request options
Section titled “Useful request options”this.http.get<Report>('/api/reports/heavy', { timeout: 5000, // aborts the backend request after 5s priority: 'low', // fetch priority hint, helps Core Web Vitals transferCache: true, // reuse the SSR-fetched response during hydration credentials: 'include', // send cookies cross-origin});One caveat the documentation is explicit about: timeout applies to the backend request only. It is not a deadline for the whole chain, so delays introduced by interceptors are not counted. For an end-to-end deadline, use RxJS timeout() at the call site.
keepalive: true lets a request outlive the page that started it — the right option for analytics and logging beacons that must survive navigation away.
Error handling
Section titled “Error handling”HttpClient routes every failure into HttpErrorResponse on the observable’s error channel, and the distinction inside it matters:
- Network and timeout errors have
status === 0and anerrorthat is aProgressEvent. - Backend errors have the real HTTP status and the parsed error body in
error.
So status === 0 means “the request never got an answer” — offline, DNS failure, CORS rejection, timeout — and everything else means “the server answered, unhappily.” Those need different handling and different messages:
private handle(error: HttpErrorResponse): Observable<never> { if (error.status === 0) { return throwError(() => new AppError('network', 'Could not reach the server.')); } if (error.status === 404) { return throwError(() => new AppError('not-found', 'That order no longer exists.')); } if (error.status >= 500) { return throwError(() => new AppError('server', 'Something went wrong on our side.')); } return throwError(() => new AppError('request', error.error?.message ?? 'Request failed.'));}Translate at the boundary. A component should not be inspecting HTTP status codes, and a user should never see one.
Retries, done properly
Section titled “Retries, done properly”Blind retry(3) hammers a struggling server and retries things that will never succeed:
const RETRYABLE = new Set([0, 408, 429, 502, 503, 504]);
export function retryInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { if (req.method !== 'GET') { return next(req); // never blind-retry a mutation }
return next(req).pipe( retry({ count: 3, delay: (error: HttpErrorResponse, retryCount) => RETRYABLE.has(error.status) ? timer(Math.min(1000 * 2 ** (retryCount - 1), 8000)) : throwError(() => error), }), );}Three rules encoded there, and all three matter:
- Only idempotent methods. Retrying a
POSTcan create two orders. If a mutation must be retryable, the server needs an idempotency key. - Only retryable statuses. A 400 or a 403 will fail identically on the third attempt.
- Exponential backoff with a cap. Tight retries against an overloaded service are a self-inflicted denial of service.
Interceptors
Section titled “Interceptors”Interceptors are middleware. Functional interceptors are recommended over the DI-based kind because their ordering is more predictable.
export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { const token = inject(AuthService).getAuthToken(); return next(req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }));}Key properties:
- They run in the injection context of the injector that registered them, so
inject()works in the function body. - They chain in declaration order.
withInterceptors([a, b])sends the request throughathenb, and the response back throughbthena. HttpRequestandHttpResponseare immutable. Mutate byclone()ing with the properties you want changed. This immutability is what makes most interceptors idempotent when a request is replayed by a retry.- The body is not protected from deep mutation. If an interceptor mutates the body, it must tolerate running more than once on the same request.
To read the response, transform the event stream and check the event type:
export function timingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { const started = performance.now(); return next(req).pipe( tap((event) => { if (event.type === HttpEventType.Response) { inject(Telemetry).record(req.url, performance.now() - started, event.status); } }), );}Because the interceptor is a closure over the request, responses associate with their requests naturally — no correlation id needed.
HttpContext: per-request metadata
Section titled “HttpContext: per-request metadata”Interceptors apply to everything, which is a problem when one request needs different treatment. HttpContext is a typed map carried on the request and never sent to the server:
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);export const CACHE_FOR_MS = new HttpContextToken<number>(() => 0);export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { if (req.context.get(SKIP_AUTH)) { return next(req); } const token = inject(AuthService).getAuthToken(); return next(req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }));}this.http.get('/api/public/config', { context: new HttpContext().set(SKIP_AUTH, true),});The token’s function supplies the default for requests that never set it — and using a function rather than a value means an object or array default gives each request its own instance rather than a shared one.
This is far better than the alternative everyone writes first: URL matching inside the interceptor. if (req.url.includes('/public/')) couples your auth logic to your URL layout and breaks silently the day someone adds /api/orders/public-notes.
What belongs in an interceptor
Section titled “What belongs in an interceptor”Authentication headers, token refresh, retry with backoff, response caching, error normalisation, request timing and telemetry, a global loading indicator, correlation ids, request deadlines.
What does not: anything specific to one endpoint. That belongs in the API-client service.
httpResource: HTTP as signals
Section titled “httpResource: HTTP as signals”httpResource wraps HttpClient and exposes status and response as signals, so HTTP data participates in the reactive graph:
@Component({ template: ` @if (user.isLoading()) { <spinner /> } @else if (user.error()) { <error-panel (retry)="user.reload()" /> } @else if (user.hasValue()) { <user-details [user]="user.value()" /> } `,})export class UserProfile { readonly userId = input.required<string>(); readonly user = httpResource<User>(() => `/api/users/${this.userId()}`);}Behaviour worth knowing:
- It requests eagerly, unlike
HttpClient’s cold observables. - It is reactive: when a signal read in the request function changes, it issues a new request — cancelling any request already in flight first. That is automatic protection against out-of-order responses, which is the bug most hand-rolled fetching gets wrong.
- It goes through the full HTTP stack, interceptors included.
- Reading
value()in an error state throws. Guard withhasValue(). - It uses the globally available
HttpClient; you only needprovideHttpClient()to configure features.
For anything beyond a URL, pass a request object with reactive properties:
readonly orders = httpResource<Page<Order>>(() => ({ url: '/api/orders', params: { status: this.status(), page: this.page() }, transferCache: true,}));Non-JSON responses use the typed variants: httpResource.text(), httpResource.blob(), httpResource.arrayBuffer().
Runtime validation
Section titled “Runtime validation”The parse option validates and types the response in one step:
const orderSchema = z.object({ id: z.string(), total: z.number(), status: z.enum(['pending', 'shipped', 'cancelled']),});
readonly order = httpResource(() => `/api/orders/${this.id()}`, { parse: orderSchema.parse,});The parse return type becomes the resource’s value type. This closes a real hole: http.get<Order>() is a compile-time assertion with no runtime check. If the API returns something else — a schema change, an error page with a 200, a proxy interposing HTML — TypeScript believed you and the failure surfaces somewhere far away. A schema at the boundary turns that into a clear error at the point of entry.
httpResource or HttpClient?
Section titled “httpResource or HttpClient?”Use httpResource for reads that feed the UI. You get loading, error and value states as signals, automatic cancellation, and no subscription management.
Use HttpClient for mutations — the documentation says so explicitly. A POST is a command with a definite moment of execution, not a value that reactively re-derives. A “resource” that re-runs when its params change would re-submit the order.
Caching and cancellation
Section titled “Caching and cancellation”Response caching in an interceptor
Section titled “Response caching in an interceptor”export function cachingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { const ttl = req.context.get(CACHE_FOR_MS); if (req.method !== 'GET' || ttl === 0) { return next(req); }
const cache = inject(ResponseCache); const hit = cache.get(req.urlWithParams); if (hit) { return of(hit); }
return next(req).pipe( tap((event) => { if (event.type === HttpEventType.Response) { cache.set(req.urlWithParams, event, ttl); } }), );}Key on urlWithParams, not url — otherwise every page of a paginated list shares one cache entry. And decide up front how a mutation invalidates the cache, because a stale list after a successful create is worse than no cache at all.
Cancellation
Section titled “Cancellation”Three mechanisms, all free:
switchMapcancels the previous request when a new value arrives. This is the fix for typeahead race conditions.AsyncPipe/toSignalunsubscribe on destroy, which aborts in-flight requests when the user navigates away.httpResourcecancels the outstanding request when its params change.
The bug all three prevent: request A for ?q=ab is slow, request B for ?q=abc is fast, B’s results render, then A’s arrive and overwrite them. The user sees results for a query they already moved past. mergeMap (or a hand-rolled subscribe) has this bug; switchMap does not.
Security
Section titled “Security”HttpClient handles the client half of two mechanisms. Both need server cooperation.
Cross-Site Script Inclusion attacks load your JSON endpoint as a <script> on an attacker’s page. The standard defence is to prefix JSON responses with a non-executable string, conventionally )]}',\n, so the response is not valid JavaScript. HttpClient strips this prefix automatically when parsing JSON. Your server has to emit it.
XSRF/CSRF
Section titled “XSRF/CSRF”HttpClient implements the cookie-to-header pattern: an interceptor reads a token from a cookie (default XSRF-TOKEN) and sets it as a header (default X-XSRF-TOKEN). Because the same-origin policy means only code on your domain can read that cookie, the presence of a matching header proves the request came from your application.
It is sent on mutating requests to relative and same-origin URLs, and not on GET or HEAD — deliberately, because CSRF only matters for state-changing requests, and the same-origin policy already stops an attacking page reading an authenticated GET response.
Angular’s own callout is blunt: HttpClient supports only the client half of the scheme. Your backend must set the cookie and verify the header on every eligible request; without that, the protection does nothing. The token must be unique per user and verifiable by the server — the documentation suggests a digest of the site’s authentication cookie plus a salt — so the client cannot invent one. Where several applications share a domain, give each a distinct cookie name to avoid collisions.
The rest
Section titled “The rest”- Never put API keys or secrets in client code. A token in an interceptor, an environment file, or an
InjectionTokenis in the shipped bundle and readable by anyone. - Do not disable certificate validation or use
http://for authenticated traffic, in any environment that touches real data. - Treat every response as untrusted. Validate it (
parse), and never interpolate a response field intoinnerHTMLor a<script>. - Be careful with
credentials: 'include'. It sends cookies cross-origin; combined with a permissive CORS policy on the server, that is a data-exposure path. - The server decides authorisation. An interceptor attaching a role header decides nothing.
Testing
Section titled “Testing”provideHttpClientTesting() replaces the backend so nothing leaves the process:
describe('OrderApiClient', () => { let api: OrderApiClient; let http: HttpTestingController;
beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); api = TestBed.inject(OrderApiClient); http = TestBed.inject(HttpTestingController); });
afterEach(() => http.verify());
it('requests the order by id', () => { let result: Order | undefined; api.getOrder('7').subscribe((o) => (result = o));
const req = http.expectOne('/api/orders/7'); expect(req.request.method).toBe('GET'); req.flush({ id: '7', total: 42 });
expect(result?.total).toBe(42); });
it('surfaces a friendly message when the server is unreachable', () => { let error: AppError | undefined; api.getOrder('7').subscribe({ error: (e) => (error = e) });
http.expectOne('/api/orders/7').error(new ProgressEvent('error'), { status: 0 });
expect(error?.kind).toBe('network'); });});http.verify() in afterEach fails the test if any request went unanswered — it catches both a request you did not expect and a request you forgot to flush. It is the single most valuable line in an HTTP test.
Because httpResource is built on HttpClient, it tests with exactly the same APIs.
Anti-patterns
Section titled “Anti-patterns”| Anti-pattern | Why it hurts |
|---|---|
HttpClient injected directly into components |
URLs and response shapes spread through the UI layer |
mergeMap for typeahead |
Out-of-order responses overwrite newer results |
.subscribe() inside .subscribe() |
Nested, uncancellable, error handling lost — use switchMap |
retry(3) with no predicate |
Retries 404s; hammers a failing server; can duplicate mutations |
catchError(() => of(null)) everywhere |
Silent failures; the UI shows empty instead of broken |
| URL matching inside an interceptor | Couples cross-cutting logic to URL layout |
http.get<T>() treated as validation |
It is a compile-time assertion only; add parse |
Reusing an HttpParams without reassigning |
Immutable — set returns a new instance |
Caching on url rather than urlWithParams |
Every page of a list collides |
withXhr() on the server |
Deprecated, unsafe redirect handling, DoS-prone |
| Secrets in interceptors or environment files | Published in the bundle |
Trade-offs
Section titled “Trade-offs”| Decision | Favours | Costs |
|---|---|---|
httpResource |
Signals, cancellation, loading/error states, no subscriptions | Reads only; less control over the request lifecycle |
HttpClient + RxJS |
Full operator vocabulary; correct for mutations | Subscription management; easy to race |
| Interceptor for a concern | Written once, applies everywhere | Invisible at the call site; needs HttpContext to opt out |
| Per-service handling | Explicit and local | Duplicated across services; drifts |
| Response caching | Fewer requests, faster UI | Invalidation; stale data after mutations |
| Runtime schema validation | Catches API drift at the boundary | Bundle size; a schema to maintain |
fetch backend (default) |
Modern, works where XHR does not | No upload progress events |
Senior interview scenarios
Section titled “Senior interview scenarios”“Why does nothing happen when you call this.http.get(url) and ignore the result?”
HttpClient returns cold observables — they are blueprints, and the request is dispatched on subscription. No subscriber, no request. The corollary catches people the other way too: subscribing twice sends two requests, because each subscription is independent. httpResource deliberately breaks this rule and fires eagerly, because a signal must have a value.
“A typeahead shows results for a query the user already moved past. Diagnose it.”
Out-of-order responses. The request for the earlier query is slower and lands after the later one, overwriting it. The cause is almost always mergeMap, or a manual subscribe per keystroke, neither of which cancels. switchMap unsubscribes from the previous inner observable, and unsubscribing from an HttpClient observable aborts the in-flight request — so the stale response never arrives. httpResource does the same thing automatically when its params change.
“How do you exempt one endpoint from an interceptor?”
HttpContext. Define an HttpContextToken with a default, check it in the interceptor, and set it per request at the call site. The alternative people reach for first — matching on req.url inside the interceptor — couples cross-cutting behaviour to URL structure and breaks silently when someone adds a path that happens to match the pattern.
“Explain Angular’s XSRF protection and what it does not do.”
An interceptor reads a token from the XSRF-TOKEN cookie and sends it as the X-XSRF-TOKEN header on mutating same-origin requests. Because the same-origin policy prevents another site reading that cookie, a matching header is evidence the request came from your application. GET and HEAD are excluded deliberately — CSRF only matters for state changes. Critically, Angular implements only the client half: the server must set the cookie and verify the header, the token must be unique per user and server-verifiable, and applications sharing a domain need distinct cookie names. Without the server side, the mechanism protects nothing.
“When would you not use httpResource?”
For mutations. POST, PUT, PATCH and DELETE are commands with a definite moment of execution; a resource is a value that re-derives when its inputs change, which for a mutation would mean re-submitting. Also when you need operator-level control the resource does not expose — a specific retry policy, sequencing several dependent calls, or combining streams — though there you can still keep httpResource for the read and use HttpClient for the orchestration.
“http.get<Order>() compiles. Is the response an Order?”
No. The generic is a compile-time assertion; nothing checks the payload at runtime. If the API changes a field, or a proxy returns an HTML error page with a 200, TypeScript believes the annotation and the failure appears somewhere unrelated with a confusing message. httpResource’s parse option runs a real schema validation at the boundary and types the value from the schema’s output, which turns a distant mystery into an immediate, located error.
Related pages
Section titled “Related pages”- Signals and Angular Reactivity
- Dependency Injection in Angular
- Angular Testing: From First Test to Large Suites
- Route Resolvers
- HTTP basics