Sub topic 9
Refreshing data with reload()
This chapter assumes you can create a resource() with a params function and a loader. It also assumes you know the status values from the earlier chapters on status and templates. Here you will use reload() to fetch the same data again. You will also see how that differs from a params change, and where it can go wrong.
When params do not change
A resource re-runs its loader when a signal read inside params changes. Sometimes the inputs stay the same but the server data has changed. Examples are a "Refresh" button, a poll every 30 seconds, or a refetch after a save. No signal changed, so the resource has no reason to run again.
reload() covers this case. It runs the loader again with the current params and returns a boolean.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-list',
template: `
<button (click)="refresh()">Refresh</button>
<p>{{ todos.value().length }} todos</p>
`,
})
export class TodoListComponent {
readonly todos = resource({
defaultValue: [] as Todo[],
loader: async ({ abortSignal }) => {
const res = await fetch('/api/todos', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
refresh() {
const started = this.todos.reload();
console.log('reload started:', started);
}
}reload() does not evaluate params again as a new request. It uses the current params value and starts the loader once more.
The reloading status
A params change and a reload both start a fetch, but the resource reports them differently.
| Trigger | Status while running | `value()` while running | `isLoading()` |
|---|---|---|---|
| First load | `loading` | `undefined`, or `defaultValue` | `true` |
| Params change | `loading` | Reset to `undefined`, or `defaultValue` | `true` |
| `reload()` | `reloading` | Keeps the previous value | `true` |
The rule is that new inputs mean the old value is no longer valid, so it is cleared. A reload asks the same question again, so the old answer stays visible until the new one arrives. Once the loader succeeds, the status becomes resolved and the value is replaced. If it fails, the status becomes error.
The error --> loading arrow shows the retry path. A failed resource can start again with reload() or by changing a signal that params reads.
Showing stale data during a reload
isLoading() is true for both loading and reloading. If your template uses the isLoading() branch from the earlier chapters, it replaces the list with "Loading..." on every refresh. The list disappears and comes back, which looks like a flicker.
To keep the data on screen, check hasValue() first and treat status() as a separate signal for the refresh indicator.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-panel',
template: `
<button (click)="todos.reload()" [disabled]="todos.isLoading()">
{{ todos.status() === 'reloading' ? 'Refreshing...' : 'Refresh' }}
</button>
@if (todos.error()) {
<p>Could not load todos.</p>
}
@if (todos.hasValue()) {
<ul>
@for (todo of todos.value(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
} @else if (todos.isLoading()) {
<p>Loading...</p>
}
`,
})
export class TodoPanelComponent {
readonly todos = resource({
loader: async ({ abortSignal }) => {
const res = await fetch('/api/todos', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
}The error message and the list are separate @if blocks on purpose. After a failed reload you may want to keep the last good list next to the message. Whether a failed resource still exposes its old value depends on the Angular version. Check hasValue() and the release notes for the version you use before relying on that behavior.
What the return value means
reload() returns true if it started a reload and false if it could not. It cannot start in two situations:
- The resource is
idle. There are no params to load with, so there is nothing to repeat. - The resource is already
loading. A fetch is in flight, and a second one would not add anything.
A call from resolved or error is accepted. A call during reloading is the case to check in your Angular version. The reference documentation describes the method as returning false when a reload cannot happen, so read it for the exact conditions.
A false return is not an exception, and nothing is logged. If it matters that the click did something, check the result.
refresh() {
if (!this.todos.reload()) {
// idle or already loading: nothing was started
return;
}
this.lastRefreshRequested = new Date();
}Disabling the button with [disabled]="todos.isLoading()" prevents most of these calls before they happen.
Reload and cancellation
A reload uses the same machinery as any other load, so the abortSignal you pass to fetch still works. If a params change arrives while a reload is running, the resource aborts the reload and starts a load for the new params. The aborted fetch rejects with an AbortError, which the resource ignores because that request was superseded. If the component is destroyed, the resource aborts its pending request as well.
For this to work, the loader must hand abortSignal to the request. A loader that ignores it still finishes in the background. The resource discards its result, but the network call and the server work are wasted.
Refreshing on a schedule
A poll is reload() on a timer. You must stop the timer when the component is destroyed. Otherwise the interval keeps running and keeps the component reachable.
import { Component, DestroyRef, inject, resource } from '@angular/core';
interface Status {
healthy: boolean;
checkedAt: string;
}
@Component({
selector: 'app-health',
template: `
@if (health.hasValue()) {
<p>{{ health.value().healthy ? 'OK' : 'Down' }} at {{ health.value().checkedAt }}</p>
}
`,
})
export class HealthComponent {
readonly health = resource({
loader: async ({ abortSignal }) => {
const res = await fetch('/api/health', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Status;
},
});
constructor() {
const timer = setInterval(() => this.health.reload(), 30_000);
inject(DestroyRef).onDestroy(() => clearInterval(timer));
}
}The timer ignores the return value on purpose. If a load is still running when the next tick arrives, reload() returns false and the tick is skipped. This stops slow responses from piling up requests.
Refetching after a write
After a POST or DELETE, the list on screen is out of date. There are two common fixes:
- Wait for the write to succeed, then call
reload()on the affected resource. This is simple and always matches the server, but it costs one more request. - Apply the change locally first with
set()orupdate(), then optionally reload to confirm. This feels faster but means the screen can briefly show data the server has not accepted.
Local writes are covered in the next chapter. Choose option 1 unless the delay is noticeable to users.
async addTodo(title: string) {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
this.todos.reload();
}reload() on rxResource and httpResource
rxResource and httpResource return the same resource object, so reload() works the same way. It resubscribes to the stream Observable, or reissues the HTTP request, with the current params. Both follow the same rules for reloading, for the boolean result, and for cancellation. The only difference is how the in-flight request is cancelled. rxResource unsubscribes from the Observable, and httpResource cancels the underlying HTTP request.
Common mistakes
- Calling
reload()to react to a signal. If a signal should trigger a fetch, read it inparams. Usereload()only when the inputs are the same and the server data may differ. - Expecting
value()to be cleared. Duringreloadingit still holds the old value. Code that treats "has a value" as "is up to date" will show stale data without any indicator. - Branching only on
isLoading(). This hides existing data during every refresh. Usestatus() === 'reloading'orhasValue()where you want to keep it visible. - Ignoring the return value in logic that depends on it.
falsemeans nothing started, so anything that waits for a new result will wait forever. - Polling without cleanup. Always clear the timer with
DestroyRef.
Exercise
A resource shows a user list. A user clicks "Refresh" while the first load is still in progress. What does reload() return, and what does the user see?
Show answer
reload() returns false because the resource is already loading, so no new request starts. The first load continues and the user sees the loading state until it finishes.
Exercise
Your template shows "Loading..." whenever isLoading() is true, and users complain that the list vanishes each time they press Refresh. Which two signals would you read instead, and what does each one decide?
Show answer
Read hasValue() to decide whether to keep rendering the list, because the value is kept during a reload. Read status() === 'reloading' to decide whether to show a small refresh indicator or to disable the button. Show the full "Loading..." message only when there is no value yet.
Exercise
A resource's params returns { id: this.userId() }. You call reload() after userId changes from 1 to 2 and the load for user 2 has already started. What happens to the earlier request, and why should the loader use abortSignal?
Show answer
The params change already started a load for user 2, so the status is loading and reload() returns false. The request for user 1 was aborted when the params changed. If the loader passes abortSignal to fetch, the browser cancels that request. If it does not, the request keeps running and its result is thrown away.