Sub topic 2
Reading value, status, and error
Assume you know Angular signals, components, templates, and async/await. A resource wraps an asynchronous read and exposes its result through signals. Read those signals by calling them, such as users.value().
Reading resource state
A resource can be idle, loading, resolved, reloading, locally changed, or in an error state. The most useful signals are:
| Signal | Meaning |
|---|---|
| `value()` | The latest successful or local value |
| `hasValue()` | Whether a usable value exists |
| `isLoading()` | Whether a request is currently running |
| `status()` | The detailed resource state |
| `error()` | The failure from the latest request |
Use hasValue() before assuming that value() exists. A resource may have no value during its first request. During a reload, it can have both an existing value and isLoading() === true.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
@if (user.error(); as error) {
<p>Could not load the user: {{ error }}</p>
<button (click)="user.reload()">Try again</button>
} @else if (user.isLoading() && !user.hasValue()) {
<p>Loading user...</p>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
<button (click)="user.reload()">Refresh</button>
}
`,
})
export class UserComponent {
readonly userId = signal(1);
readonly user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const response = await fetch(`/api/users/${params.id}`, {
signal: abortSignal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return (await response.json()) as User;
},
});
}Rendering every state
Check errors before values when a failed request leaves an older value available. Check hasValue() before calling value(). During a refresh, keep showing the old value and add a small loading indicator instead of replacing the whole page with “Loading.”
Handling failures
error() contains the thrown value, often an Error, but it can be another type. Display a safe message or map the error to a user-facing message. A failed resource does not automatically retry. reload() starts the loader again.
Refreshing data with `reload()`
Call reload() after a user requests fresh data or after a mutation succeeds. It runs the loader again without changing the parameters. Treat the result as asynchronous state: the template may briefly show the previous value while the reload is active.
Exercise
Why might a template check both isLoading() and hasValue()?
Show answer
The first request has no value yet, while a reload can be loading and still have a previous value to display.