Sub topic 11
Cancelling and Combining Requests
This chapter assumes you know RxJS pipe, the TodoService from earlier chapters, and how toSignal turns an Observable into a signal. It covers two jobs that come up in almost every real screen. The first is stopping a request when its answer is no longer wanted. The second is coordinating several requests whose results belong together.
How cancellation works in HttpClient
An Observable returned by HttpClient is cold. Nothing goes over the network until something subscribes, and each new subscription sends a new request. The reverse also holds. If you unsubscribe before the response arrives, Angular aborts the underlying request (an XMLHttpRequest, or a fetch call when you use withFetch()). In the browser DevTools Network tab, the request shows as "(canceled)".
import { Subscription } from 'rxjs';
// Inside a component that injects TodoService
private sub?: Subscription;
load(): void {
this.sub = this.todoService.getTodos(1).subscribe(todos => console.log(todos));
}
stop(): void {
this.sub?.unsubscribe(); // aborts the request if it is still in flight
}You rarely call unsubscribe() by hand. Operators such as switchMap and takeUntil, the async pipe, toSignal, and takeUntilDestroyed all unsubscribe for you, and each of those unsubscriptions cancels the request.
Cancelling when a component is destroyed
toSignal and the async pipe clean up when the component is destroyed. If you subscribe manually, use takeUntilDestroyed from @angular/core/rxjs-interop. Called inside an injection context, such as a field initializer or the constructor, it needs no arguments.
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-count',
template: `<p>{{ count }} todos</p>`
})
export class TodoCountComponent {
private readonly todoService = inject(TodoService);
count = 0;
constructor() {
this.todoService
.getTodos(1)
.pipe(takeUntilDestroyed())
.subscribe((todos: Todo[]) => (this.count = todos.length));
}
}If the user leaves the page before the response arrives, the request is aborted and the callback never runs against a destroyed component.
Search-as-you-type with switchMap
The standard cancellation example is a search box. Each keystroke could start a request, and responses can come back out of order. If the user types "wr" and then "write", the response for "wr" might arrive last and overwrite the correct results. switchMap fixes this. When a new value arrives, it unsubscribes from the previous inner Observable, which cancels that HTTP request, and then subscribes to the new one.
Add a search method to TodoService:
// Inside TodoService
searchTodos(term: string): Observable<Todo[]> {
const params = new HttpParams().set('q', term);
return this.http.get<Todo[]>(`${this.baseUrl}/search`, { params });
}Then build the component:
// todo-search.component.ts
import { Component, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, distinctUntilChanged, of, switchMap } from 'rxjs';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="query" placeholder="Search todos" />
<ul>
@for (todo of results(); track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>No matches.</li>
}
</ul>
`
})
export class TodoSearchComponent {
private readonly todoService = inject(TodoService);
readonly query = new FormControl('', { nonNullable: true });
readonly results = toSignal(
this.query.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term =>
term.trim().length < 2
? of([] as Todo[])
: this.todoService.searchTodos(term).pipe(
catchError(() => of([] as Todo[]))
)
)
),
{ initialValue: [] as Todo[] }
);
}Each operator in the pipe has its own job:
debounceTime(300)waits until the user pauses typing, so most keystrokes never start a request.distinctUntilChanged()skips a request when the term has not changed, for example after typing a character and deleting it.switchMapcancels the outdated request when a newer term arrives.catchErrorsits on the inner Observable. If you put it on the outer pipe instead, one failed search would complete the whole stream and the box would stop working.
Choosing a flattening operator
switchMap is one of four operators that map each value to an inner Observable. They differ in what happens when a new value arrives while an earlier request is still in flight.
| Operator | When a new value arrives during a request | Typical HTTP use |
|---|---|---|
| `switchMap` | Cancels the current request and starts the new one | Search, filters, route parameter changes |
| `mergeMap` | Starts the new request in parallel | Independent requests where order does not matter |
| `concatMap` | Queues the new request until the current one finishes | Saves that must reach the server in order |
| `exhaustMap` | Ignores the new value until the current one finishes | Submit or "Save" buttons that users double-click |
The usual mistake is using switchMap for writes. If a user toggles a todo twice quickly, switchMap aborts the first PUT on the client, but the server may already have applied it. The client then cannot tell what state the server is in. For writes, choose concatMap to keep every change in order, or exhaustMap to drop repeat clicks.
// todo-editor.component.ts
import { Component, inject, input } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, exhaustMap } from 'rxjs';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-editor',
template: `<button (click)="save$.next()">Save</button>`
})
export class TodoEditorComponent {
private readonly todoService = inject(TodoService);
readonly todo = input.required<Todo>();
readonly save$ = new Subject<void>();
constructor() {
this.save$
.pipe(
exhaustMap(() => this.todoService.updateTodo(this.todo())),
takeUntilDestroyed()
)
.subscribe(saved => console.log('Saved', saved.id));
}
}Clicking Save five times sends one PUT. Clicks that arrive while that PUT is in flight are discarded.
Running requests in parallel with forkJoin
A screen often needs several independent pieces of data before it can render. forkJoin subscribes to all of its inputs at once, waits for every one to complete, and then emits a single value with each input's last value. HttpClient Observables emit once and complete, so forkJoin fits them well. Passing an object instead of an array gives you named, typed results.
// dashboard.component.ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, forkJoin, of } from 'rxjs';
import { Todo, TodoService } from './todo.service';
interface UserProfile {
id: number;
name: string;
}
@Component({
selector: 'app-dashboard',
template: `
@if (data(); as d) {
<h2>Hello, {{ d.profile?.name ?? 'guest' }}</h2>
<p>{{ d.todos.length }} todos on page 1</p>
} @else {
<p>Loading…</p>
}
`
})
export class DashboardComponent {
private readonly http = inject(HttpClient);
private readonly todoService = inject(TodoService);
readonly data = toSignal(
forkJoin({
todos: this.todoService.getTodos(1),
profile: this.http
.get<UserProfile>('/api/me')
.pipe(catchError(() => of(null)))
})
);
}The data signal starts as undefined, which the @else branch handles, and becomes { todos, profile } once both responses arrive. The two requests run in parallel, so the total wait is roughly the slower of the two responses, not their sum.
forkJoin failure modes
- One error fails everything. If any input errors,
forkJoinerrors right away and unsubscribes from the others, which cancels their requests. PutcatchErroron each input that may fail without breaking the page, asprofiledoes above. - An input that never completes blocks forever. A plain HTTP call always completes. A
Subject,valueChangesorintervalpassed toforkJoinnever does, soforkJoinnever emits. - An input that completes without emitting. If an input completes empty, for example
EMPTYreturned from acatchError,forkJoincompletes without emitting anything. Returnof(fallback)instead ofEMPTY.
Dependent requests
When the second request needs data from the first, chain them with a flattening operator instead of nesting subscribe calls. Nested subscriptions cannot be cancelled as a unit, and they split error handling across several places.
// Inside a component that injects HttpClient as `http`
interface Project {
id: number;
ownerId: number;
}
readonly owner = toSignal(
this.http.get<Project>('/api/projects/7').pipe(
switchMap(project => this.http.get<UserProfile>(`/api/users/${project.ownerId}`))
)
);To fan out, for example to load details for every id in a list, combine the two patterns. switchMap to a forkJoin of the detail requests. Guard against an empty list, because forkJoin([]) completes immediately without emitting.
// Inside a component that injects HttpClient as `http`; also import `map` from 'rxjs'
readonly details = toSignal(
this.http.get<number[]>('/api/todos/ids').pipe(
switchMap(ids =>
ids.length === 0
? of([] as Todo[])
: forkJoin(ids.map(id => this.http.get<Todo>(`/api/todos/${id}`)))
),
map(todos => todos.filter(t => !t.completed))
),
{ initialValue: [] as Todo[] }
);For long lists, a fan-out like this can send hundreds of requests at once. Browsers limit connections per host, and many servers rate-limit clients. Use mergeMap with its concurrency argument, or better, a batch endpoint.
Avoiding accidental duplicate requests
Because HttpClient Observables are cold, two subscribers mean two requests. Binding the same Observable with async in two places in a template sends the request twice. Convert it once with toSignal and read the signal wherever you need it. Alternatively, apply shareReplay({ bufferSize: 1, refCount: true }) to the Observable so later subscribers reuse the first response.
Exercise
A "Mark complete" button calls updateTodo through switchMap. Users report that a todo sometimes looks incomplete after they click the button twice quickly, even though the server shows it as complete. Explain the cause and pick a better operator.
Show answer
switchMap aborted the first PUT on the client after the server had already applied it. The UI then only tracked the second request, which may have failed or been ignored, so the client and server state disagree. Use exhaustMap to ignore clicks while a save is in flight, or concatMap if every click must be sent in order.
Exercise
A component uses forkJoin({ todos: getTodos(1), stats: this.http.get('/api/stats') }). The stats endpoint sometimes returns 500, and the whole dashboard goes blank. Rewrite the stats input so the todos still render.
Show answer
Add catchError to the stats input only and return a fallback value: stats: this.http.get<Stats>('/api/stats').pipe(catchError(() => of(null))). Do not return EMPTY, because forkJoin would then complete without emitting.
Exercise
In the search component, catchError is moved from the inner searchTodos call to the end of the outer pipe. What happens after the first failed search?
Show answer
The error reaches the outer stream. catchError replaces it with its fallback Observable, and the original valueChanges chain completes. Later keystrokes no longer trigger searches. The catchError must stay on the inner Observable so that only the single failed request is replaced.