Sub topic 5
Cancelling stale requests
This chapter assumes you know how to create a resource with a params function and a loader, and that you are comfortable with fetch, Promises, and signals.
The stale request problem
A resource re-runs its loader whenever a signal read inside params changes. Suppose a user clicks through ids 1, 2, and 3 quickly. Three requests are now in flight, and they can finish in any order. If the request for id 1 finishes last, an old response could overwrite the newer one.
The resource prevents this. It only accepts the result of the most recent load. Responses from superseded loads are ignored, even when they arrive late.
Ignoring a response does not stop the network call, though. The browser still sends the request and the server still does the work. To stop that work, pass the abortSignal to your request.
What abortSignal is
The loader receives an object with params and abortSignal. The abortSignal is a standard AbortSignal, the same type fetch accepts. The resource aborts it when any of these happens:
- The signals read in
paramschange while the loader is still running. - You call
reload()while a load is in progress. - The component that owns the resource is destroyed.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-picker',
template: `
<button (click)="next()">Next user</button>
@if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ user.value()?.name }}</p>
}
`,
})
export class UserPickerComponent {
readonly userId = signal(1);
readonly user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as User;
},
});
next() {
this.userId.update((id) => id + 1);
}
}Each click on the button changes userId. The resource aborts the running fetch and starts a new one. The aborted fetch rejects with an AbortError, which the resource discards because that load is already superseded. You do not need to catch it.
The sequence of events
Forgetting to pass the signal
If you leave out { signal: abortSignal }, the code still behaves correctly in the UI. The resource still ignores stale results. The cost is hidden: every superseded request runs to completion, which wastes bandwidth and server capacity. Nothing warns you, so it is easy to miss.
Other data sources
- Libraries other than fetch: Many HTTP clients accept an
AbortSignaloption. Check the documentation and pass it along. - rxResource: The resource unsubscribes from the Observable, and
HttpClientcancels the underlying request on unsubscribe. You pass nothing extra. - httpResource: It is built on
HttpClient, so superseded requests are cancelled the same way.
Exercise
A resource loader calls fetch without passing abortSignal. The user changes the params signal three times in a row. What does the UI show, and what happens to the first two requests?
Show answer
The UI shows only the result of the third request, because the resource ignores results from superseded loads. The first two requests are not cancelled. They still run to completion and their responses are thrown away. Passing { signal: abortSignal } to fetch would cancel them.