Sub topic 2
Why hand-written loading and error state breaks down
This chapter assumes you know TypeScript and async/await, Angular components and templates, signals (signal, computed, effect), and the basics of HttpClient. It shows the problems that the resource API, covered in the next chapters, is designed to remove.
The usual hand-written pattern
Most components that load data keep three or four fields next to each other: the data, a loading flag, an error, and the input that decides what to load. Here is a version with signals.
import { Component, effect, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-manual',
template: `
@if (error()) {
<p>Could not load the user.</p>
} @else if (loading()) {
<p>Loading...</p>
} @else {
<p>{{ user()?.name }}</p>
}
`,
})
export class UserManualComponent {
readonly userId = signal(1);
readonly user = signal<User | undefined>(undefined);
readonly loading = signal(false);
readonly error = signal<unknown>(undefined);
constructor() {
effect(() => {
const id = this.userId();
this.load(id);
});
}
private async load(id: number) {
this.loading.set(true);
this.error.set(undefined);
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
this.user.set((await res.json()) as User);
} catch (e) {
this.error.set(e);
} finally {
this.loading.set(false);
}
}
}This looks reasonable and works for a single, slow-moving request. The problems appear when the input changes quickly or when the request fails.
Where it breaks
Out-of-order responses
Suppose userId changes from 1 to 2 and then to 3. Three requests are in flight. If the response for user 2 arrives after the response for user 3, user.set runs last with the wrong user. The screen shows user 2 while userId() is 3. Nothing in the code prevents this, because each call to load is independent.
Stale requests keep running
Even when the late response is ignored, the browser still performs the old request. Without an AbortController, you cannot cancel it. Adding one means storing the controller, aborting it before each new load, and handling the resulting AbortError so it does not show up as a real failure.
Flags that disagree
The finally block of an old request sets loading to false while a newer request is still running. The template then shows stale or empty content with no spinner. The fields user, loading, and error are separate signals, so nothing keeps them consistent. You can also reach impossible combinations, such as loading and error both set, or an old user shown beside a new error.
Writing to signals inside an effect
The example uses effect to start the load. The load itself writes to signals, and effects are meant to propagate state out, not to produce it. Angular lets you do this, but it is easy to create loops or ordering surprises. Each component also repeats the same wiring.
Repetition
Every data source needs the same four fields, the same try/catch/finally, and the same cancellation logic. Copies drift apart, and each copy needs its own tests.
| Problem | Hand-written fix | Cost |
|---|---|---|
| Out-of-order responses | Compare a request counter before `set` | Extra bookkeeping in every loader |
| Wasted requests | Store and abort an `AbortController` | Must filter `AbortError` |
| Inconsistent flags | Update all fields in one place | Easy to forget a branch |
| Repeated wiring | Shared base class or helper | Another abstraction to maintain |
What a resource changes
A resource ties the input, the request, and the state together. It re-runs when the signals it reads change, cancels the superseded request, and exposes value, status, and error as signals that always describe the latest request. The next chapter builds the first one.
Exercise
In the hand-written component, userId changes from 1 to 2 while the request for user 1 is still running. Name two things that can go wrong, even though each request ends in a normal response.
Show answer
First, if the response for user 1 arrives after the one for user 2, it overwrites the user signal and the screen shows the wrong user. Second, the finally block of the request for user 1 sets loading to false while the request for user 2 is still running, so the spinner disappears too early. The request for user 1 also keeps running because nothing aborts it.