Sub topic 1
Why HttpClient Returns Observables
Every HttpClient method (get, post, put, patch, delete, request) returns an RxJS Observable instead of a Promise. This choice affects how you write every data call in an Angular app. It decides when a request is sent, how it gets cancelled, how retries work, and what happens when two parts of your UI read the same data.
This chapter explains how an HttpClient Observable behaves, why Angular picked it, and the mistakes developers usually make when they first use it. The later chapters on services, error handling and components assume you know this behavior.
Prerequisites
This chapter assumes you already know:
- TypeScript interfaces and generics, such as
Observable<Todo[]>. - Angular components, services and dependency injection with
inject(). - How a standalone Angular application is bootstrapped.
- What an RxJS
Observableis, howsubscribeworks, and how to chain operators withpipe. - HTTP methods, status codes and JSON payloads.
The examples assume HttpClient is already registered with provideHttpClient(). The next chapter covers that setup.
The contract of an HttpClient Observable
An Observable returned by HttpClient follows a small, predictable contract:
- It is cold and lazy. Nothing goes over the network until something subscribes.
- Each subscription sends its own request. Subscribe twice and the server receives two requests.
- In the default mode it emits one value and then completes. The value is the parsed response body.
- A failure arrives on the error channel. You get an
HttpErrorResponseand no value. Error and completion are both terminal. - Unsubscribing before the response arrives aborts the request. The underlying XHR or
fetchcall is cancelled.
The sequence below shows one subscription from start to finish.
Laziness: calling `get` does not send a request
A Promise starts working when it is created. An HttpClient Observable is only a description of a request. That description runs each time someone subscribes.
// lazy-demo.component.ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Todo {
id: number;
title: string;
completed: boolean;
}
@Component({
selector: 'app-lazy-demo',
template: `<button (click)="load()">Load todos</button>`
})
export class LazyDemoComponent {
private readonly http = inject(HttpClient);
// Building the Observable sends nothing.
private readonly todos$ = this.http.get<Todo[]>('/api/todos');
load(): void {
// Every click subscribes again, so every click sends a new GET.
this.todos$.subscribe(todos => console.log(`Loaded ${todos.length} todos`));
}
}Open the browser's Network tab and click the button three times. You will see three requests. The Observable was created once, but it was subscribed three times.
Laziness lets you build, pass around and decorate a request before it runs. A service can return this.http.get(...), and the caller can add retry, map or catchError before anything is sent. A Promise cannot do this, because by the time you hold one the request is already underway.
One subscription, one request
The other side of laziness is that duplicate subscriptions send duplicate requests. This often happens by accident in templates:
<p>Total: {{ (todos$ | async)?.length }}</p>
<ul>
@for (todo of todos$ | async; track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>Each async pipe subscribes separately, so this template sends two GET requests. You can fix it in one of these ways:
- Subscribe once, for example with a single
@if (todos$ | async; as todos)block, and readtodosinside it. - Convert the Observable to a signal once with
toSignaland read the signal as often as you like. A later chapter covers this. - Share the result explicitly with
shareReplay:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, shareReplay } from 'rxjs';
export interface Country {
code: string;
name: string;
}
@Injectable({ providedIn: 'root' })
export class CountryService {
private readonly http = inject(HttpClient);
// One request, no matter how many subscribers, for the app's lifetime.
readonly countries$: Observable<Country[]> = this.http
.get<Country[]>('/api/countries')
.pipe(shareReplay({ bufferSize: 1, refCount: false }));
}Use shareReplay only for data that is fine to cache, such as reference lists. If the request fails, shareReplay does not cache the error. The next subscriber triggers a new request.
Cancellation comes built in
Unsubscribing from an in-flight HttpClient Observable aborts the HTTP request. A plain Promise has no standard way to do this.
import { Component, OnDestroy, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-report',
template: `
<button (click)="start()">Generate report</button>
<button (click)="cancel()">Cancel</button>
`
})
export class ReportComponent implements OnDestroy {
private readonly http = inject(HttpClient);
private sub?: Subscription;
start(): void {
this.cancel();
this.sub = this.http
.get('/api/reports/slow', { responseType: 'text' })
.subscribe(report => console.log('Report ready', report.length));
}
cancel(): void {
this.sub?.unsubscribe(); // Aborts the request if it is still running.
}
ngOnDestroy(): void {
this.cancel();
}
}The browser shows the cancelled request as "(canceled)". Whether the server stops working on it depends on the server. The client just stops waiting. RxJS operators use the same mechanism. switchMap unsubscribes from the previous inner request when a new value arrives, so a type-ahead search drops stale results. takeUntilDestroyed() from @angular/core/rxjs-interop unsubscribes when a component is destroyed. A later chapter covers composing requests this way.
Retries work because the Observable is cold
The retry operator works by resubscribing to the source after an error. Each subscription runs the request again, so a resubscription is a real second request:
this.http.get<Todo[]>('/api/todos').pipe(retry(2));
// Up to 3 GET requests in total: the original plus two retries.A Promise has already settled once it rejects. To retry it, you would need a function that creates a new Promise. Observables give you this behavior through a single operator. The error handling chapter builds on it with catchError and HttpErrorResponse.
More than one value: events and progress
In the default observe: 'body' mode you get one value. The Observable type still allows several values, and HttpClient uses that. With observe: 'events' and reportProgress: true, one request emits a sequence of HttpEvent objects: a "sent" event, upload and download progress events, a header event, and the final HttpResponse. A Promise resolves exactly once, so it cannot represent this. Later chapters cover the observe option and progress events.
Observables compared with Promises
| Behavior | HttpClient Observable | `fetch` / Promise |
|---|---|---|
| When the request starts | On `subscribe` | When the Promise is created |
| Running the same call twice | Each subscription sends a request | You must call the function again |
| Cancellation | `unsubscribe()` aborts it | Requires a manual `AbortController` |
| Retry | `retry(n)` operator | A hand-written loop that creates new Promises |
| Number of values | One by default, many with `observe: 'events'` | Exactly one |
| Transforming and combining | RxJS operators (`map`, `switchMap`, `forkJoin`) | `then` chains, `Promise.all` |
| Interceptors | A pipeline of Observables | Not built in |
When you really need a Promise
Some APIs expect a Promise, such as route resolvers you write with async, or code you share with a non-Angular library. Convert the Observable with firstValueFrom or lastValueFrom from RxJS:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
interface Settings {
theme: 'light' | 'dark';
}
@Injectable({ providedIn: 'root' })
export class SettingsService {
private readonly http = inject(HttpClient);
async loadSettings(): Promise<Settings> {
// Subscribes, waits for the single value, and rejects on HttpErrorResponse.
return firstValueFrom(this.http.get<Settings>('/api/settings'));
}
}Converting gives up cancellation and lazy composition. Keep Observables throughout the app and convert only at the edge where a Promise is required. Do not use the deprecated toPromise().
Common errors
- Forgetting to subscribe. The request never runs. This is easy to miss with POST and DELETE calls, because nobody reads their result.
- Subscribing inside
subscribe. Nested subscriptions are hard to cancel and they hide errors. UseswitchMap,concatMaporforkJoininstead. - Several
asyncpipes on one Observable. This sends duplicate requests. Subscribe once or share the result. - Expecting a cached value. Without
shareReplayor a signal, a later subscriber gets a fresh request, not the earlier result. - Assuming
unsubscribeundoes a write. Aborting a POST stops the client from waiting. The server may have already saved the data.
Exercise
A component defines user$ = this.http.get<User>('/api/me') and its template uses {{ (user$ | async)?.name }} in the header and {{ (user$ | async)?.email }} in the sidebar. How many requests are sent when the component loads, and how would you change the code so only one is sent?
Show answer
Two GET requests are sent, because each async pipe subscribes separately and each subscription to a cold HttpClient Observable sends its own request. To send one, subscribe once. You can convert it to a signal with user = toSignal(this.http.get<User>('/api/me')) and read user()?.name and user()?.email. You can wrap both uses in one @if (user$ | async; as user) block. Or you can add shareReplay({ bufferSize: 1, refCount: true }) to the Observable.
Exercise
A save handler calls this.http.post('/api/notes', note); with no other code on that line, and the note never appears on the server. The browser console shows no error. Explain why.
Show answer
HttpClient Observables are lazy. Calling post only builds a description of the request, and nothing subscribed to it, so no request was sent and no error was raised. Add .subscribe(), or pipe the call through an operator that subscribes, such as switchMap in a larger stream, so the POST runs.
Exercise
Why does this.http.get('/api/data').pipe(retry(3)) send up to four requests, while retrying a rejected Promise needs extra code?
Show answer
retry resubscribes to the source after an error. HttpClient Observables are cold, so each subscription runs a new HTTP request: the original plus three retries. A Promise represents one operation that has already started and settled, so a rejected Promise cannot run again. To retry it, you must call a function that creates a new Promise.