Sub topic 5
Cancelling stale requests
This chapter assumes you can create a resource with a reactive params function and an async loader, as covered earlier. It explains what happens when the params change while a request is still running. It also shows how to pass the abortSignal to fetch and to your own async code.
The stale request problem
Suppose a user clicks through several records quickly. Each click changes a signal, and each change starts a new request. Responses do not always arrive in the order the requests were sent. If request 1 is slow and request 2 is fast, the answer to request 1 can arrive last. Code that blindly stores every response would then show data for record 1 while the user is looking at record 2. This is a race condition.
A resource prevents the display problem for you. When the signals read in params change, the resource starts a new load and marks the earlier one as superseded. The result of a superseded load is discarded, even if its promise still resolves later. The value() signal can therefore only hold the result of the most recent load.
Discarding the result does not stop the work. Without more help, the old HTTP request keeps running. The browser keeps the connection open, the server keeps working, and the response is downloaded and thrown away. The abortSignal lets you cancel that work.
How abortSignal works
The loader receives an object with three properties: params, abortSignal, and previous. The abortSignal is a standard [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal), the same type the web platform uses for cancellable operations. Each load gets its own signal.
The resource aborts the signal of the running load in these cases:
- The
paramsfunction produces a new value, so a newer load replaces the running one. - You call
reload()while a load is in flight, which starts a replacement load. - You call
set()while a load is in flight. The local value wins, and the load is cancelled. - The owning component or injector is destroyed, so nobody is left to use the result.
Passing the signal to fetch completes the picture. When the signal aborts, fetch rejects its promise with an AbortError and the browser cancels the network request.
import { Component, resource, signal } from '@angular/core';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-product',
template: `
<button (click)="productId.set(productId() + 1)">Next product</button>
@if (product.isLoading()) {
<p>Loading...</p>
} @else if (product.hasValue()) {
<p>{{ product.value().name }}</p>
}
`,
})
export class ProductComponent {
readonly productId = signal(1);
readonly product = resource({
params: () => ({ id: this.productId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/products/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Product;
},
});
}Clicking the button three times in a row starts three loads. The first two are aborted, and only the third can deliver a value.
The sequence looks like this.
What happens to the AbortError
When fetch rejects with an AbortError, you might expect the resource to enter the error state. It does not. The rejection belongs to a load that has already been superseded, so the resource ignores it. Your error() signal reflects only the current load.
You do not need a try/catch around fetch to filter out aborts. Catch errors only when you want to translate them, and rethrow anything you do not handle.
Cancelling work that is not fetch
fetch accepts a signal directly, but other asynchronous work does not. Timers, WebSocket requests, IndexedDB reads, and third-party SDK calls need manual wiring. The pattern is to listen for the abort event and undo the work there.
A common use is a debounce. Waiting a short time before sending a request avoids a flood of calls while the user types. Because the resource aborts the previous load whenever the params change, the pending wait is cancelled automatically, provided the wait listens to the signal.
import { Component, resource, signal } from '@angular/core';
interface SearchResult {
id: number;
title: string;
}
function delay(ms: number, signal: AbortSignal): Promise<void> {
return new Promise<void>((resolve, reject) => {
signal.throwIfAborted();
const timer = setTimeout(resolve, ms);
signal.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
}
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" placeholder="Search" />
@if (results.isLoading()) {
<p>Searching...</p>
}
<ul>
@for (item of results.value(); track item.id) {
<li>{{ item.title }}</li>
}
</ul>
`,
})
export class SearchComponent {
readonly query = signal('');
readonly results = resource({
defaultValue: [] as SearchResult[],
params: () => (this.query().trim() ? { q: this.query().trim() } : undefined),
loader: async ({ params, abortSignal }) => {
await delay(300, abortSignal);
const res = await fetch(`/api/search?q=${encodeURIComponent(params.q)}`, {
signal: abortSignal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as SearchResult[];
},
});
}Typing "angular" produces seven param changes. Each new keystroke aborts the previous load. Because of the delay, only the load that survives 300 milliseconds without a new keystroke reaches fetch. The other six never send a request.
Two details in this example matter. signal.throwIfAborted() handles the case where the signal is already aborted before the promise is created. The { once: true } option removes the listener after it fires. The function also returns undefined from params when the query is empty, which keeps the resource idle instead of searching for nothing.
Cancellation in rxResource and httpResource
The other two resource types handle cancellation for you.
| API | How the superseded request is cancelled |
|---|---|
| `resource` | You pass `abortSignal` to `fetch` or to your own code. |
| `rxResource` | The resource unsubscribes from the previous Observable. `HttpClient` cancels the underlying request on unsubscribe. |
| `httpResource` | The resource issues the request through Angular's HTTP stack and cancels it when the request signal changes. |
With rxResource, the loader is a stream function, so there is no abortSignal to pass. The unsubscribe is what cancels the work. If your Observable wraps something that is not cancellable on unsubscribe, return a teardown function from the Observable constructor.
Gotchas
- Forgetting the signal is silent. The resource still shows the correct data because it discards stale results. The only symptoms are wasted network traffic and slower servers, so review loaders for a missing
signal: abortSignal. - Not every endpoint is safe to abort. Aborting a
GETis harmless. For a request that changes data on the server, an abort only stops the browser from waiting. The server may still complete the operation. Resources are meant for reads, so keep writes out of loaders. - Cancellation is not retry. An aborted load is never retried. The newer load takes its place.
- Work after the last await is not cancelled. If your loader does CPU-heavy processing after
fetchresolves, nothing interrupts it. CheckabortSignal.abortedbetween steps if the work is long.
Checking your understanding
Exercise
A resource loader calls fetch('/api/items/' + params.id) without passing abortSignal. The user changes id from 1 to 2 before the first response arrives. What does value() show when both responses have arrived, and what is the cost of the missing signal?
Show answer
value() shows the data for id 2, because the resource discards the result of the superseded load whether or not the signal is used. The cost is that the request for id 1 is not cancelled. The browser and the server still do all its work, and its response is downloaded and thrown away. The fix is fetch(url, { signal: abortSignal }).
Exercise
In the search example, the user types "a", waits one second, then types "ab". How many requests reach the server, and why?
Show answer
Two. The load for "a" survives the 300 ms delay and sends its request. When "ab" arrives, that load is aborted, which cancels its request if it is still in flight. The new load waits 300 ms and sends a second request. Cancelling the first request does not prevent it from reaching the server, so the count of requests sent is two.
Exercise
Why does an aborted fetch not put the resource into the error state?
Show answer
The AbortError is raised by a load that has already been superseded. The resource only reports errors from the current load, so the rejection of the old one is ignored.