Sub topic 1
Signals in two minutes
Prerequisites
Assume you know TypeScript, async/await, Angular components and templates, and the basics of signal, computed, effect, HttpClient, and RxJS.
An Angular signal is a reactive value. Read it by calling it, such as count(). Change it with set() or update(). Angular tracks reads and can rerun dependent code when the value changes.
Why hand-written loading and error state breaks down
A manual request often needs separate fields for data, loading, and error. Every request must reset them in the correct order. Rapid changes can also let an older response overwrite a newer one. This repeated coordination is easy to get wrong.
A resource combines asynchronous work with signal-based state. It tracks the request inputs, exposes the result and status, and can cancel work that is no longer current.
Your first resource
A resource has a loader function. The loader receives parameters and an AbortSignal, which lets the request be cancelled.
Reacting to signals with params and loader
The params function is reactive. When it reads userId, Angular runs the loader again after userId changes.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
@if (user.isLoading()) {
<p>Loading...</p>
} @else if (user.error()) {
<p>Could not load the user.</p>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
}
`,
})
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;
},
});
}Cancelling stale requests
Pass abortSignal to fetch. If userId changes while a request is pending, Angular aborts the superseded request. The newer request becomes the active one.
Exercise
Why should the loader pass its abortSignal to fetch?
Show answer
It allows Angular to cancel an obsolete request when the reactive parameters change.