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). The previous chapter created a resource with a loader. Here you will see how a resource decides when to run that loader again.
The two functions and who watches what
A resource takes two functions that do different jobs.
paramsis a reactive function. Angular tracks every signal you read inside it, as it does in acomputed. When any of them changes, the resource notices.loaderis an async function that does the work. Angular does not track signals read inside it. It runs whenparamsproduces a new value, and it receives that value.
Here is a complete example:
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);
}
}The params function reads userId(), so the resource depends on userId. Each click on the button changes userId. The resource then runs params again, gets a new object, and calls loader with it.
What the loader receives
The loader gets one argument, an object with these properties:
| Property | Meaning |
|---|---|
| `params` | The value your `params` function returned. TypeScript infers its type. |
| `abortSignal` | An `AbortSignal` that fires when this request is superseded or the resource is destroyed. |
| `previous` | An object with the `status` the resource had before this load started. |
You do not need to read signals in the loader to get the current inputs, because params already carries them. This is why the loader takes params as an argument instead of reaching into this.
Why signals read in the loader are not tracked
A common mistake is to read a signal directly inside the loader:
import { Component, resource, signal } from '@angular/core';
interface Item {
id: number;
label: string;
}
@Component({
selector: 'app-items',
template: `
<button (click)="page.set(page() + 1)">Next page</button>
<p>{{ stale.value()?.length }} / {{ correct.value()?.length }}</p>
`,
})
export class ItemsComponent {
readonly page = signal(1);
// Wrong: page() is read in the loader, so the resource never reloads on page changes.
readonly stale = resource({
loader: async ({ abortSignal }) => {
const res = await fetch(`/api/items?page=${this.page()}`, { signal: abortSignal });
return (await res.json()) as Item[];
},
});
// Right: page() is read in params and passed to the loader.
readonly correct = resource({
params: () => ({ page: this.page() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/items?page=${params.page}`, { signal: abortSignal });
return (await res.json()) as Item[];
},
});
}The first resource loads page 1 once and then ignores the button. The loader runs outside the tracking context, partly because it is async. Signal reads after the first await could never be tracked reliably. Keeping the dependencies in params makes them explicit and keeps the loader a plain function of its input.
When params produces a new value
The params function behaves like a computed, so it re-evaluates only when a signal it read has changed. Two details follow from that.
- Several changes in a row produce one load. The resource starts its loader from an effect, not synchronously. If you set
userIdthree times in the same synchronous block, the loader runs once, with the last value. - A new object counts as a change. Returning
{ id: this.userId() }creates a new object every timeparamsre-evaluates. The resource compares results by reference. This normally causes no extra loads, becauseparamsonly re-evaluates whenuserIdhas changed. If you read a signal and write the same value back, the signal itself does not notify, so nothing reloads.
Status during a params-driven reload
When params changes, the resource moves to the loading status and the previous value is discarded. value() returns undefined, or your defaultValue if you set one. This differs from reload(), covered in a later chapter. That method keeps the current value and uses the reloading status.
This affects your template. If you switch from user 1 to user 2, the component shows the loading branch, not user 1's name with a spinner beside it. If you want the old value to stay visible, you need to hold it yourself, for example in a separate signal, or use reload() for refreshes of the same input.
The status values you will meet are:
idle: no valid params, and nothing has loaded.loading: the first load, or a load after params changed.reloading: a load started byreload(), with the old value still available.resolved: the loader finished andvalue()holds the result.error: the loader threw or its promise rejected.local: the value was set locally withset()orupdate().
Skipping the load with undefined
If params returns undefined, the loader does not run. The resource moves to idle. This is how you express "not ready yet", for example while the user has not chosen anything:
import { Component, resource, signal } from '@angular/core';
interface Detail {
id: string;
title: string;
}
@Component({
selector: 'app-detail',
template: `
@if (selectedId() === null) {
<p>Pick an item.</p>
} @else if (detail.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ detail.value()?.title }}</p>
}
`,
})
export class DetailComponent {
readonly selectedId = signal<string | null>(null);
readonly detail = resource({
params: () => {
const id = this.selectedId();
return id === null ? undefined : { id };
},
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/details/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Detail;
},
});
}TypeScript narrows params in the loader to the non-undefined type, so params.id needs no check. If params later goes back to undefined, the resource returns to idle, the value is cleared, and any request in flight is aborted.
Cancellation and superseded requests
Whenever params produces a new value, or the owning component is destroyed, the resource aborts the previous abortSignal. Passing that signal to fetch cancels the network request. Without it, the old request still finishes. The resource ignores its result, because it only accepts the result of the latest load. You would still waste bandwidth and server work. A later chapter covers cancellation in detail. For now, pass abortSignal to every fetch call.
Edge cases to know
- Throwing in
params. An exception insideparamsis treated like any computed error. Keepparamsfree of side effects and of code that can throw. Do parsing and validation in the loader, where errors become the resource'serrorstate. - Reading the resource's own value in params. Do not do this, because it creates a cycle. Read another resource's value instead, as the dependent resources chapter shows.
- Non-signal inputs. A plain class field is not tracked. If
paramsreadsthis.pageSizeand that field is a number, changing it does nothing. Make it a signal, or a signal-basedinput(). - Untracked reads. If you want
paramsto ignore a signal, wrap the read inuntracked()from@angular/core. - Resource creation context. Create the resource in an injection context, such as a field initializer or a constructor. It needs one to tie its lifetime to the component.
Exercise
A component has readonly query = signal('') and a resource whose loader calls fetch('/api/search?q=' + this.query()) with no params function. The user types in a search box that updates query. Why does the search never re-run, and how do you fix it so it also does not search while query is an empty string?
Show answer
The loader runs outside any tracking context, so reading this.query() there does not make the resource depend on it. Move the read into params and return undefined for an empty string: params: () => { const q = this.query(); return q === '' ? undefined : { q }; }. Change the loader to take { params, abortSignal } and fetch '/api/search?q=' + encodeURIComponent(params.q) with { signal: abortSignal }. The resource now reloads when query changes and stays idle while it is empty.
Exercise
A resource goes from user 1 to user 2 because userId changed. During the load, what do status() and value() return, and how does that differ from calling reload()?
Show answer
After a params change, status() is loading and value() is undefined, or the defaultValue if you set one. The previous value is discarded. After reload(), status() is reloading and value() keeps the old value until the new load finishes.