Sub topic 2
Working with HttpClient Observables
This chapter assumes you know Angular standalone components, inject(), and the operators pipe, map, and filter.
HttpClient Returns Cold Observables
HttpClient.get() returns an observable that sends no request until something subscribes to it. Each new subscription sends a new request. When the response arrives, the observable emits one value and completes. If you unsubscribe before then, Angular cancels the request.
Handling Errors with catchError and retry
retry(n) resubscribes up to n times after an error. Because the observable is cold, each resubscription sends the request again. catchError swaps the error for a fallback observable, such as of([]).
The most common mistake is to put catchError on the outer stream. Once an error reaches the outer stream, that stream completes and never emits again. To keep the outer stream alive, attach catchError to the inner request.
Choosing a Flattening Operator
A flattening operator maps each outer value to an inner observable and subscribes to that inner observable for you.
| Operator | Behavior when a new value arrives | Typical use |
|---|---|---|
| `switchMap` | Cancels the previous inner observable | Search, route params |
| `mergeMap` | Runs inner observables in parallel | Independent saves |
| `concatMap` | Queues them and runs one at a time, in order | Ordered writes |
| `exhaustMap` | Ignores new values while one is running | Login button |
A Debounced Search
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { catchError, debounceTime, distinctUntilChanged, filter, of, retry, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
standalone: true,
imports: [ReactiveFormsModule, AsyncPipe],
template: `
<input [formControl]="query" />
@for (r of results$ | async; track r) { <li>{{ r }}</li> }
`,
})
export class SearchComponent {
private http = inject(HttpClient);
query = new FormControl('', { nonNullable: true });
results$ = this.query.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
switchMap(term =>
this.http.get<string[]>('/api/search', { params: { q: term } }).pipe(
retry(2),
catchError(() => of([]))
)
)
);
}debounceTime waits for a 300 ms pause in typing, and distinctUntilChanged drops a term that is the same as the previous one. switchMap then cancels any request that is still running when a newer term arrives.
Route Parameters
When the user navigates between routes that use the same component, Angular reuses that component instance. Read paramMap as a stream so the component picks up the new parameter instead of keeping the old one:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs';
@Component({
selector: 'app-product',
standalone: true,
imports: [AsyncPipe],
template: `<p>{{ (product$ | async)?.name }}</p>`,
})
export class ProductComponent {
private http = inject(HttpClient);
product$ = inject(ActivatedRoute).paramMap.pipe(
switchMap(p => this.http.get<{ name: string }>(`/api/products/${p.get('id')}`))
);
}Exercise
You place catchError(() => of([])) after switchMap in the search stream instead of inside it. What happens after the first failed request?
Show answer
The error replaces the outer stream with of([]). The stream emits [] and completes, so later keystrokes no longer trigger any searches.
Exercise
Which flattening operator stops a double-clicked "Pay" button from sending two payment requests?
Show answer
exhaustMap. It ignores new clicks while the first request is still in flight.