Sub topic 6
Reading value, status, and error
A resource exposes its state as signals. This chapter covers what each signal holds in each phase of a request, and how to read them without hitting a surprise. I assume you know signal, computed, and effect, and that you have created a resource with params and a loader, as in the earlier chapters.
The signals on a resource
Every resource (resource, rxResource, and httpResource) returns an object with the same read-only signals:
value()holds the latest data, orundefinedif there is none. If you setdefaultValue, it holds that instead.status()holds one of six states, listed below.error()holds the error from the last failed load, orundefined.isLoading()is a convenience signal that istruewhile a request is in flight.hasValue()returnstruewhen the resource currently has a usable value. It also narrows the TypeScript type ofvalue().
All of these are signals, so reading them inside a template, a computed, or an effect registers a dependency. When the resource moves to a new state, everything that read these signals updates.
The six statuses
status() is the one signal that tells you exactly where the resource is. The other signals are views of it.
| Status | Meaning | `value()` | `isLoading()` |
|---|---|---|---|
| `idle` | `params` returned `undefined`, so no request is made | `undefined` or `defaultValue` | `false` |
| `loading` | First load, or a load after `params` changed | `undefined` or `defaultValue` | `true` |
| `reloading` | A load started by `reload()` | The previous value | `true` |
| `resolved` | The loader finished successfully | The loaded data | `false` |
| `error` | The loader threw or rejected | Not readable (see below) | `false` |
| `local` | Someone called `set()` or `update()` | The locally written data | `false` |
The difference between loading and reloading matters in practice. When params changes, the old value belongs to a different input, so the resource discards it and goes to loading. When you call reload(), the input is the same and the old data is still a good approximation, so the resource keeps it and goes to reloading. This lets you show the old data with a small refresh indicator instead of a blank screen.
Reading value safely
value() returns undefined before the first load finishes. That is why the first example in this tutorial wrote user.value()?.name. There are three ways to deal with it.
- Use optional chaining, as above. This is the simplest option and works everywhere.
- Set
defaultValue, for exampledefaultValue: [] as Todo[]. The type ofvalue()no longer includesundefined, sotodos.value().lengthcompiles without a guard. - Check
hasValue()first. Inside theif, TypeScript knowsvalue()is notundefined.
if (this.user.hasValue()) {
// value() is typed as User here, not User | undefined
console.log(this.user.value().name);
}The dependent-resource example from the spine uses this form: this.user.hasValue() ? { userId: this.user.value().id } : undefined.
hasValue() is not the same as status() === 'resolved'. It is also true in reloading and local, because the resource holds data in those states. It is false in idle, loading, and error.
Reading error
error() is only meaningful when status() is error. It holds whatever the loader threw. In a fetch loader, a network failure rejects with a TypeError, but an HTTP 404 or 500 does not reject at all. The Promise resolves with res.ok set to false. That is why every loader in this tutorial contains if (!res.ok) throw new Error(...). Without that line, a 500 response would be parsed as JSON and end up in value() with status resolved.
The type of error() depends on your Angular version. It may be unknown or Error | undefined. Narrow it before using it:
import { computed } from '@angular/core';
readonly errorMessage = computed(() => {
const err = this.user.error();
return err instanceof Error ? err.message : 'Unknown error';
});The error is cleared when the next load starts, so a retry through reload() or a params change takes the resource out of error.
A complete status view
The component below renders every status. It uses @switch on status() so that each state has exactly one branch, and it never reads value() in the error branch.
import { Component, computed, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-status',
template: `
<button (click)="next()">Next user</button>
<button (click)="user.reload()">Reload</button>
<button (click)="rename()">Rename locally</button>
<p>Status: {{ user.status() }}</p>
@switch (user.status()) {
@case ('idle') {
<p>Nothing requested.</p>
}
@case ('loading') {
<p>Loading user...</p>
}
@case ('reloading') {
<p>Refreshing {{ user.value()?.name }}...</p>
}
@case ('error') {
<p>Failed: {{ errorMessage() }}</p>
}
@case ('resolved') {
<p>{{ user.value()?.name }}</p>
}
@case ('local') {
<p>Edited: {{ user.value()?.name }}</p>
}
}
`,
})
export class UserStatusComponent {
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;
},
});
readonly errorMessage = computed(() => {
const err = this.user.error();
return err instanceof Error ? err.message : 'Unknown error';
});
next() {
this.userId.update((id) => id + 1);
}
rename() {
this.user.update((u) => (u ? { ...u, name: 'Renamed' } : u));
}
}Click "Next user" and watch the status label. It shows loading, then resolved, with the old name gone in between. Click "Reload" and it shows reloading with the old name still visible. Click "Rename locally" and it shows local with no request sent.
Choosing between status, isLoading, and error
Use isLoading() when you only need a spinner. It is true for both loading and reloading, so it cannot tell a first load from a refresh. Use status() when the UI differs between those cases, or when you need to separate idle from loading. Use error() when you only need to know whether to show an error message.
A common mistake is to combine them as @if (user.isLoading()) ... @else { {{ user.value().name }} }. That fails in two ways. In the idle state, value() is undefined. In the error state, reading it may throw. Branch on error() first, then isLoading(), then the value, as the spine's first example does.
Another mistake is treating local as a failure of the loader or as stale data. local only says that the current value came from set() or update() and not from the loader. The next reload() or params change replaces it with loaded data.
Reading status in code
Because the status is a signal, you can derive from it with computed. Here is a flag that is true only on the first load, so you can show a skeleton screen once and then keep the data on screen afterwards:
readonly isInitialLoad = computed(() => this.user.status() === 'loading');Remember that loading also occurs when params changes, so this flag also fires when the user switches to another ID. That is often the behavior you want, because the old user's data has been discarded.
You can also read status inside an effect, for example to log failures. Keep side effects like that small, and do not write to signals from them unless you have a specific reason.
Exercise
A resource has status reloading. What are value(), isLoading(), and hasValue(), and why does the resource use reloading instead of loading here?
Show answer
value() is the previous value, isLoading() is true, and hasValue() is true. The resource uses reloading because reload() repeats a request with the same params, so the old data is still a reasonable thing to display. When params changes, the old data belongs to a different input, so the status is loading and the value is cleared.
Exercise
Your template contains @if (user.isLoading()) { <p>Loading</p> } @else { <p>{{ user.value().name }}</p> }. Name two states in which the @else branch misbehaves, and say how to fix it.
Show answer
In idle, value() is undefined, so .name fails. In error, reading value() may throw in recent Angular versions. Fix it by checking error() first, then isLoading(), and only then reading the value, using value()?.name or a hasValue() guard.