Sub topic 11
Cancelling and Combining Requests
This chapter assumes you can write a typed HttpClient GET call in a service and display the result with the async pipe or toSignal. You should also know the RxJS pipe method. Here you will learn how to cancel requests that are no longer needed and how to run several requests together.
Cancellation Is Unsubscription
An HttpClient Observable sends its request when you subscribe to it. If you unsubscribe before the response arrives, Angular aborts the underlying browser request. You never call a separate "cancel" API. Ending the subscription is the cancellation.
This matters most when one user action makes an earlier request out of date. A search box is the usual example. A user types "mi", then "mil", then "milk". You want only the result for "milk". If an older response arrives late, it must not replace the newer one.
Dropping Stale Requests with switchMap
switchMap maps each incoming value to a new inner Observable. When a new value arrives, it unsubscribes from the previous inner Observable first. With HttpClient, that unsubscription aborts the request that is still in flight.
// todo-search.component.ts
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
import { Todo } from './todo.service';
@Component({
selector: 'app-todo-search',
imports: [ReactiveFormsModule, AsyncPipe],
template: `
<input [formControl]="query" placeholder="Search todos" />
<ul>
@for (todo of (results$ | async) ?? []; track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
`
})
export class TodoSearchComponent {
private readonly http = inject(HttpClient);
readonly query = new FormControl('', { nonNullable: true });
readonly results$ = this.query.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term =>
this.http.get<Todo[]>('/api/todos', {
params: new HttpParams().set('q', term)
})
)
);
}debounceTime(300) waits until the user stops typing for 300 ms. distinctUntilChanged() skips a value if it equals the previous one. switchMap makes sure only the newest search is still running.
Choosing a Flattening Operator
switchMap is the right choice for reads, but it can be dangerous for writes. Pick the operator based on what should happen when a new trigger arrives while a request is still running.
| Operator | Behaviour on a new value | Typical use |
|---|---|---|
| `switchMap` | Cancels the previous request | Search, route-driven loads |
| `concatMap` | Queues it until the previous one completes | Saves that must run in order |
| `mergeMap` | Runs all requests in parallel | Independent bulk operations |
| `exhaustMap` | Ignores it until the current request completes | Submit buttons, login |
Running Requests in Parallel with forkJoin
Sometimes a screen needs data from several endpoints before it can render. forkJoin subscribes to all of its inputs at once. When every input completes, it emits each one's last value. HttpClient Observables emit once and then complete, so they work well with forkJoin.
// dashboard.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, catchError, forkJoin, of } from 'rxjs';
import { Todo } from './todo.service';
export interface User {
id: number;
name: string;
}
export interface Dashboard {
user: User;
todos: Todo[];
}
@Injectable({ providedIn: 'root' })
export class DashboardService {
private readonly http = inject(HttpClient);
load(): Observable<Dashboard> {
return forkJoin({
user: this.http.get<User>('/api/me'),
todos: this.http
.get<Todo[]>('/api/todos')
.pipe(catchError(() => of([] as Todo[])))
});
}
}If you pass an object, the result has the same keys. That keeps the types clear and avoids depending on array order.
Common Errors
- Using
switchMapfor a save action. A second click aborts the first save, and you can't know whether the server applied it. - Nesting
subscribecalls insidesubscribe. Nested subscriptions can't be cancelled as a group. Use a flattening operator. - Feeding
forkJoinan empty array or object. It completes at once without emitting any value.
Exercise
A "Place order" button sends a POST each time it is clicked. Users double-click it and create duplicate orders. Which operator should map clicks to the POST request, and why not switchMap?
Show answer
Use exhaustMap. While the first POST is still running, it ignores any further clicks, so only one order is sent. switchMap would abort the first request when the second click arrives. The server might still create the first order, and then the second request creates another.
Exercise
You combine three GET requests with forkJoin. One endpoint returns a 500. What does the subscriber receive, and how can you still render the other two results?
Show answer
The subscriber receives only an error, and forkJoin cancels any requests that are still pending. Add catchError to the failing (optional) request so it returns a fallback value such as of(null) or of([]). forkJoin then emits all three values.