Sub topic 6
Working with HttpClient Observables
Angular's HttpClient returns observables instead of Promises. That choice affects when requests are sent, how many times they are sent, and how you cancel them. This chapter explains how an HttpClient observable behaves, how to configure requests and read responses, and which mistakes come up most often.
This chapter assumes you know the observable, observer, and subscription model from the first chapter, can use pipe with map and tap, and understand why unsubscribing matters. Error recovery, flattening operators, and sharing a request between subscribers each get their own chapter later. Here they come up only where they affect how an HTTP observable behaves.
Setting Up HttpClient
In a standalone application, you register HttpClient once in the application config. withFetch() makes Angular use the browser's Fetch API instead of XMLHttpRequest. Angular recommends it, especially for server-side rendering.
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withFetch())],
};After this, any service or component can call inject(HttpClient).
The Shape of an HTTP Observable
An HttpClient observable has the following properties. Most bugs come from forgetting one of them.
| Property | What it means in practice |
|---|---|
| Cold | Nothing is sent until something subscribes. |
| One request per subscription | Two subscribers cause two network requests. |
| Emits once, then completes | You get one `next` with the body (by default), then `complete`. |
| Errors are terminal | A failed status (such as 404 or 500) arrives through `error`, and the stream ends. |
| Unsubscribe aborts | Unsubscribing before the response arrives cancels the request in flight. |
The diagram below follows one subscription from start to finish.
Because the observable completes after one emission, a plain subscribe to an HttpClient call does not leak memory once the response arrives. Unsubscribing still matters for a different reason. If the user leaves a page while a slow request is pending, the callback runs after the component is gone, unless you cancel. That is why the async pipe and takeUntilDestroyed are still the defaults for HTTP calls.
Cold means lazy
This snippet sends no request:
import { inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const http = inject(HttpClient); // inside an injection context
http.post('/api/logout', {}); // builds an observable, sends nothingpost only describes the request. Nobody subscribed, so nothing goes over the network. This is the opposite of fetch(), which starts its request as soon as you call it.
One subscription, one request
The reverse problem is subscribing more than once by accident:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-summary',
standalone: true,
imports: [AsyncPipe],
template: `
<p>Total: {{ (users$ | async)?.length }}</p>
<p>First: {{ (users$ | async)?.[0]?.name }}</p>
`,
})
export class UserSummaryComponent {
private http = inject(HttpClient);
users$ = this.http.get<User[]>('/api/users');
}Each async pipe is its own subscriber, so this template sends GET /api/users twice. To fix it, use one @if (users$ | async; as users) block and read users inside it. The chapter on cold and hot observables shows how shareReplay lets several independent subscribers reuse one request.
Typing Responses
The generic on get<T>() tells TypeScript what the body looks like:
this.http.get<User[]>('/api/users'); // Observable<User[]>Configuring Requests
The last argument of every method is an options object. The options you will use most are params, headers, observe, and responseType.
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: number;
name: string;
price: number;
}
@Injectable({ providedIn: 'root' })
export class ProductApi {
private http = inject(HttpClient);
private base = '/api/products';
list(page: number, category?: string): Observable<Product[]> {
let params = new HttpParams().set('page', page);
if (category) {
params = params.set('category', category);
}
return this.http.get<Product[]>(this.base, { params });
}
create(product: Omit<Product, 'id'>): Observable<Product> {
const headers = new HttpHeaders({ 'X-Request-Source': 'admin-ui' });
return this.http.post<Product>(this.base, product, { headers });
}
update(product: Product): Observable<Product> {
return this.http.put<Product>(`${this.base}/${product.id}`, product);
}
remove(id: number): Observable<void> {
return this.http.delete<void>(`${this.base}/${id}`);
}
}HttpParams and HttpHeaders are immutable. set returns a new instance, so params.set('category', category) alone does nothing. You have to reassign the result, as the code above does. This is a common source of "my query parameter is missing" bugs. You can also pass a plain object, such as { params: { page, category } }, which avoids the problem when every value is defined.
The service returns observables and never subscribes. The caller decides when the request runs and when to cancel it. Keep this pattern for every API service.
Reading the full response
By default, you receive only the parsed body. To read the status code or headers, pass observe: 'response':
import { HttpResponse } from '@angular/common/http';
import { map } from 'rxjs';
listWithTotal(page: number) {
return this.http
.get<Product[]>(this.base, { params: { page }, observe: 'response' })
.pipe(
map((res: HttpResponse<Product[]>) => ({
items: res.body ?? [],
total: Number(res.headers.get('X-Total-Count') ?? 0),
}))
);
}observe: 'events' goes further and emits progress events, which helps with upload progress bars. It needs reportProgress: true. With observe: 'events', the stream emits more than once.
For non-JSON bodies, set responseType: 'text' or responseType: 'blob'. The return type then changes to Observable<string> or Observable<Blob>, and you cannot pass a generic.
Cancellation in Practice
Cancelling by unsubscribing is the main thing observables give you over Promises in HTTP code. Angular's own tools use it automatically:
- The async pipe unsubscribes when the component is destroyed, which aborts a pending request.
takeUntilDestroyed()does the same for manual subscriptions.switchMapunsubscribes from the previous inner request when a new value arrives. The flattening and search chapters build on this.
You can see the abort in the browser's network tab. The request shows as "(canceled)". Keep in mind that the server may already have processed it. Cancelling a POST stops your client from handling the response. It does not undo the side effect on the server.
Interceptors
An interceptor is a function that sees every request before it leaves and every response before it arrives. Functional interceptors work naturally with observables because next(req) returns the response stream, and you can pipe onto it.
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { tap } from 'rxjs';
import { AuthStore } from './auth.store';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthStore).token();
const authReq = token
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
: req;
const started = performance.now();
return next(authReq).pipe(
tap({
finalize: () =>
console.debug(`${req.method} ${req.url} ${Math.round(performance.now() - started)}ms`),
})
);
};// app.config.ts
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withFetch(), withInterceptors([authInterceptor]))],
};Requests are immutable, so you modify them with clone. AuthStore stands for whatever service holds your token. In this example it exposes a signal. Interceptors run in the order they are listed for requests, and in reverse order for responses.
Common Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| No request in the network tab | Nothing subscribed to the observable | Subscribe, or bind it with the async pipe |
| Duplicate requests | Several subscribers to the same cold observable | Use one subscription point, or share with `shareReplay` |
| Query parameter missing | `HttpParams.set` result was discarded | Reassign: `params = params.set(...)` |
| Runtime `undefined` despite correct types | Generic type does not match the real JSON | Validate or `map` the body at the boundary |
| Callback runs after navigating away | Manual subscribe without cancellation | Use the async pipe or `takeUntilDestroyed()` |
| Service subscribes internally and returns nothing | Callers lose control over timing and cancellation | Return the observable from the service |
Exercise
A component calls this.api.remove(id) in a click handler, where remove returns this.http.delete<void>(url), but the item is never deleted on the server and no error appears. What is wrong, and what is the minimal fix?
Show answer
The observable returned by delete is cold, and nobody subscribes to it, so no request is sent. Subscribe in the handler, for example this.api.remove(id).subscribe(). Because the observable completes after one response, this does not leak. To cancel when the component is destroyed, add takeUntilDestroyed(this.destroyRef) before subscribing.
Exercise
You need both the list of orders and the X-Total-Count header from GET /api/orders. Write the HttpClient call that returns an Observable<{ orders: Order[]; total: number }>.
Show answer
this.http.get<Order[]>('/api/orders', { observe: 'response' }).pipe(map(res => ({ orders: res.body ?? [], total: Number(res.headers.get('X-Total-Count') ?? 0) }))). The observe: 'response' option gives you an HttpResponse<Order[]>, and map reshapes it.
Exercise
A template uses (stats$ | async)?.visits in three places, and stats$ is a plain http.get call. How many requests are sent on load, and why?
Show answer
Three requests are sent. Each async pipe subscribes separately, and each subscription to a cold HttpClient observable sends its own request. Use a single @if (stats$ | async; as stats) block, or share the stream with shareReplay.