Sub topic 9
Reloading and cancelling stale requests
This chapter covers two behaviors of httpResource: how it repeats a request on demand, and how it drops requests that no longer matter. It assumes you can read the value, status, error and isLoading signals and that you know how a request function depends on signals, both from earlier chapters. You should also know that httpResource uses HttpClient underneath.
Two ways a request starts again
An httpResource sends a new request for one of two reasons:
- The request changed. A signal read inside the request function has a new value, so the function returns a different URL or request object.
- You called
reload(). The request is the same, but you want fresh data from the server.
Both reasons can arrive while an earlier request is still in flight. The resource has to decide what to do with the old request, and that decision is cancellation.
Reloading with `reload()`
reload() repeats the current request without changing any signal. The response may differ even though the URL does not, for example after another user edits the record or after your own write succeeds.
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-notes',
template: `
<button (click)="notes.reload()" [disabled]="notes.isLoading()">
Refresh
</button>
@if (notes.status() === 'reloading') {
<p>Refreshing…</p>
}
<pre>{{ notes.value() }}</pre>
`,
})
export class NotesComponent {
notes = httpResource.text(() => '/assets/notes.txt');
}While the reload is running, the text that was already loaded stays visible. The user sees the old content with a small "Refreshing…" message instead of an empty page.
Loading versus reloading
The resource reports two different states for work in progress. Both make isLoading() return true, but status() tells them apart.
| Trigger | `status()` while waiting | What to show |
|---|---|---|
| First request, or the request changed | `loading` | A placeholder. The data belongs to a different request, so do not rely on the previous value. |
| `reload()` on an unchanged request | `reloading` | The current `value()` plus a subtle refresh indicator. |
The distinction exists because the two cases mean different things. After a request change, the old value answers a different question: it was user 1, and now you asked for user 2. After a reload, the old value answers the same question, so it is a good stand-in until the new one arrives.
The full set of statuses is idle, loading, reloading, resolved, error and local. The local status appears when you write to the resource with set() or update(). This chapter only needs the first five.
What `reload()` returns
reload() returns a boolean. It returns true when it started a reload and false when it did nothing. It does nothing in two situations:
- The resource is
idlebecause the request function returnedundefined. There is no request to repeat. - The resource is already
loadingorreloading. A request is already on its way.
Most code ignores the return value. It matters when you want to tell the user that a click had no effect.
refresh() {
const started = this.notes.reload();
if (!started) {
console.log('Nothing to reload: idle or already loading');
}
}Reloading also works from the error state. This makes a "Try again" button simple:
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Report {
title: string;
}
@Component({
selector: 'app-report',
template: `
@if (report.error()) {
<p>Could not load the report.</p>
<button (click)="report.reload()">Try again</button>
} @else {
<h2>{{ report.value()?.title }}</h2>
}
`,
})
export class ReportComponent {
report = httpResource<Report>(() => '/api/report');
}Cancelling stale requests
Suppose a component shows user 1, and the user clicks "Next" twice quickly. The resource now has requests for users 2 and 3 to deal with, and the request for user 2 is obsolete the moment userId becomes 3.
When the request function produces a new request, the resource unsubscribes from the in-flight HttpClient observable. In a browser, HttpClient aborts the underlying network call when that happens. The response for the outdated request is never written into value(). You do not write any cancellation code for this.
The diagram below shows this order of events.
Why this matters
Without cancellation, two responses could arrive out of order. A slow answer for user 2 could land after the fast answer for user 3, and the page would show the wrong user while the URL says 3. This is a race condition, and it is a common bug in hand-written subscribe code. A resource avoids it because only one request per resource is ever allowed to write the result.
The same rule applies to reload(). If a request is in flight and the request function then changes, the in-flight request is cancelled and replaced. If the component is destroyed first, the pending request is cancelled too.
Typing in a search box
Cancellation is most visible with a search field that sends a request on every keystroke:
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-live-search',
template: `
<input (input)="query.set($any($event.target).value)" />
@if (results.isLoading()) {
<p>Searching…</p>
}
<ul>
@for (p of results.value(); track p.id) {
<li>{{ p.title }}</li>
}
</ul>
`,
})
export class LiveSearchComponent {
query = signal('');
results = httpResource<Product[]>(
() => {
const q = this.query();
return q ? { url: '/api/products', params: { q } } : undefined;
},
{ defaultValue: [] },
);
}Typing "angular" produces up to seven requests. Each new keystroke cancels the one before it, so at most one response ever reaches the list. The code is correct, but it still sends a request per keystroke. If the server is slow or costly, reduce the traffic by debouncing the query signal before the request function reads it. The resource handles ordering. It does not decide how often you ask.
Edge cases and gotchas
- Cancellation is client-side. The browser stops waiting and aborts the call. The server may already have received the request and may finish its work. This is harmless for reads. It is one more reason not to run writes through a resource.
- A cancelled request is not an error. The
error()signal stays empty. The resource simply moves on to the newer request. - Setting a signal to the same value does nothing. Signals ignore writes that do not change the value.
userId.set(3)when it is already 3 sends no request. Usereload()when you want the same request again. reload()does not queue. Calling it five times in a row during a load starts one reload, and the other four calls returnfalse.- Idle resources cannot reload. If the request function returns
undefined, there is nothing to repeat. Fix the input signal first. - Do not read the previous value after a request change. Check
hasValue()orstatus()before usingvalue()for anything other than display, and treat the value as unavailable whilestatus()isloading. - Reads inside the request function are tracked. Only signals read there trigger a new request. If you need a value without causing requests when it changes, read it outside the function or wrap it in
untracked()from@angular/core.
Refreshing on a timer
Polling combines reload() with a timer. Clean up the timer when the component is destroyed. The resource cancels its own request on destroy, but the interval is yours to stop.
import { Component, DestroyRef, inject } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Status {
online: number;
}
@Component({
selector: 'app-status',
template: `<p>Online: {{ status.value()?.online }}</p>`,
})
export class StatusComponent {
status = httpResource<Status>(() => '/api/status');
constructor() {
const id = setInterval(() => this.status.reload(), 30_000);
inject(DestroyRef).onDestroy(() => clearInterval(id));
}
}If a poll fires while the previous one is still running, reload() returns false and nothing piles up.
Summary of the rules
- A changed request cancels the old request and starts a new one, with status
loading. reload()repeats the same request, with statusreloading, and keeps the existing value on screen.- Only the latest request can write
value(), so out-of-order responses cannot show stale data. - Cancellation stops the client from waiting. It does not undo work on the server.
Exercise
A page shows order = httpResource<Order>(() => /api/orders/${this.orderId()}). The user clicks a "Refresh" button, and order.reload() runs. What is status() while the reload is in flight, what happens to value(), and what does a second click during that time do?
Show answer
status() is reloading, and isLoading() is true. value() keeps the previously loaded order, so the page does not go blank. The second click calls reload() while a request is already running, so it starts nothing and returns false.
Exercise
A search resource has the request function () => ({ url: '/api/products', params: { q: this.query() } }). The user types "a", then quickly "ab". The response for "a" arrives after the response for "ab" would have. Which results does value() end up with, and why?
Show answer
It ends up with the results for "ab". Changing query to "ab" made the resource cancel the in-flight request for "a" and start a new one. Only the latest request can write value(), so the late response for "a" is dropped, and no error() is set.