Sub topic 6
Working with HttpClient Observables
This chapter assumes you know how observables, observers, and subscriptions relate, and that you can compose operators with pipe. It also assumes you are comfortable with Angular services, standalone components, and dependency injection.
Angular's HttpClient returns an observable for every request. Once you know how that observable behaves, most HTTP bugs become easy to explain.
Setting Up HttpClient
In a standalone application, you register HttpClient once when the app starts:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});After that, any service or component can call inject(HttpClient).
The Working Model
An HttpClient observable follows four rules:
| Behavior | What it means in practice |
|---|---|
| Cold | Nothing is sent until something subscribes. |
| One request per subscription | Subscribing twice sends two requests. |
| Emits once, then completes | You get one response body, then `complete`. |
| Unsubscribe cancels | Unsubscribing before the response arrives aborts the request. |
Because the observable completes after one value, a single HTTP call does not leak memory the way an endless stream would. Unsubscribing still matters, because it cancels requests the user no longer needs.
Typed Requests in a Service
Keep HTTP calls in a service and return the observable without subscribing. The caller decides when and how to subscribe.
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable, map } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`);
}
searchUsers(name: string, page = 1): Observable<User[]> {
const params = new HttpParams().set('name', name).set('page', page);
return this.http.get<User[]>('/api/users', { params });
}
getUserNames(): Observable<string[]> {
return this.http
.get<User[]>('/api/users')
.pipe(map(users => users.map(u => u.name)));
}
getUserWithHeaders(id: number): Observable<HttpResponse<User>> {
return this.http.get<User>(`/api/users/${id}`, { observe: 'response' });
}
}The generic get<User> is a compile-time assertion only. HttpClient does not check that the server's JSON matches User. If the payload shape matters for correctness, validate it in a map.
Passing observe: 'response' gives you the full HttpResponse, with status and headers, instead of just the body.
Common Errors
- Duplicate requests. Two
asyncpipes on the same HTTP observable, or a manualsubscribeplus anasyncpipe, send two requests. Subscribe once, or share the result (a later chapter coversshareReplay). - Subscribing inside the service. If the service subscribes and stores the result in a field, callers lose cancellation and have no reliable way to know when the data has arrived. Return the observable instead.
- Expecting a stream of updates. The observable will not emit again when server data changes. To refetch, subscribe again or trigger a new request from another stream.
- Building the URL with string concatenation. Use
HttpParamsor theparamsobject so that values get URL-encoded.
Exercise
A template uses {{ (user$ | async)?.name }} and {{ (user$ | async)?.id }}, where user$ = this.userService.getUser(42). How many GET requests are sent, and why?
Show answer
Two. Each async pipe subscribes on its own, and HttpClient observables are cold, so each subscription sends its own request. Subscribe once (for example with @if (user$ | async; as user)) or share the observable.
Exercise
A deleteUser(id) method returns this.http.delete('/api/users/' + id). A button handler calls this.userService.deleteUser(5); and nothing is deleted. What is the fix?
Show answer
Nothing subscribes to the returned observable, so the request is never sent. Call .subscribe() on the result, or feed it into a stream that subscribes.