Sub topic 4
Reacting to signals with params and loader
This chapter assumes you know TypeScript with async/await, Angular components and templates, and the basics of signals (signal, computed, effect). You should also have created a first resource in the previous chapter.
The two halves of a resource
A resource separates two questions:
- What data do I want? The
paramsfunction answers this. - How do I get it? The
loaderfunction answers this.
params is a reactive function. Angular tracks every signal you read inside it. When any of those signals changes, the resource runs loader again with the new params. You do not write an effect or subscribe to anything.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
<button (click)="next()">Next user</button>
@if (user.error()) {
<p>Could not load the user.</p>
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ user.value()?.name }}</p>
}
`,
})
export class UserComponent {
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. That change invalidates params, and the loader runs for the new user.
How the loader receives its input
The loader gets one argument, an object with these fields:
| Field | Meaning |
|---|---|
| `params` | The value `params` returned, captured when this load started. |
| `abortSignal` | An `AbortSignal` that fires if this load is superseded or the resource is destroyed. |
| `previous` | Information about the previous status of the resource. |
The loader runs outside the reactive tracking context. Reading a signal directly inside loader does not trigger a reload. Read every signal you depend on in params and pass the values through the params argument.
// Wrong: userId() is read in the loader, so changes are not tracked.
const bad = resource({
loader: async () => {
const res = await fetch(`/api/users/${this.userId()}`);
return res.json();
},
});
// Right: userId() is read in params, so changes re-run the loader.
const good = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params }) => {
const res = await fetch(`/api/users/${params.id}`);
return res.json();
},
});The first example would load once and never again, even though userId changes.
What happens on a change
While the new load runs, isLoading() is true. The abort step is how Angular prevents a slow, older response from overwriting a newer one. The next chapter covers abortSignal in detail.
Common errors
- Reading signals in the loader. As shown above, those reads are untracked. Move them into
params. - Ignoring
res.ok.fetchonly rejects on network failure. Throw on a bad status so the resource reports an error. - Returning a new object that looks the same.
paramsis compared by identity. Returning{ id: 1 }after recomputing from the same signals is fine, because the function only reruns when a tracked signal changes. Problems arise only when you read signals that change more often than you intend.
Exercise
A resource's loader calls fetch(/api/items?page=${this.page()}) directly, with no params function. The user changes page, but the list does not update. Why, and how do you fix it?
Show answer
The loader runs outside the reactive tracking context, so reading this.page() there does not register a dependency, and the loader ran only once. Add params: () => ({ page: this.page() }) and read params.page in the loader.