Sub topic 1
Why resources: async data as signals
Signals hold values that are available right now. Data from a server is not. This chapter explains the gap between the two, how Angular's resource API closes it, and why httpResource is built on that idea. The later chapters in this tutorial use that model without re-explaining it.
Prerequisites
This chapter assumes you already know:
- TypeScript basics, including generics,
async/awaitandPromise. - Angular components and templates, including the
@ifand@forcontrol flow blocks. - Angular signals: creating them with
signal(), deriving values withcomputed(), and reading them by calling them, such ascount(). - Basic HTTP: methods, query parameters, headers and status codes.
You do not need to know HttpClient internals. The setup chapter covers what you need.
The problem: signals are synchronous
A computed signal runs a function and returns its result immediately. That function cannot wait. If you return a Promise from it, the signal's value is the promise object, not the data inside it.
import { computed, signal } from '@angular/core';
const userId = signal(1);
// The value of `user` is a Promise, not a user.
const user = computed(() => fetch(`/api/users/${userId()}`).then((r) => r.json()));Asynchronous data has properties that a plain signal value cannot express:
- It does not exist yet when the component first renders.
- It can fail.
- It can become outdated when its inputs change while a request is still running.
- It can be refreshed while the old value is still on screen.
A signal holds one value. Async data needs a value plus a state: loading, failed, or done.
The manual workaround and its flaws
Before resources, a common pattern was an effect that watched a signal and wrote the result into other signals.
import { Component, effect, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-manual-user',
template: `<p>{{ user()?.name }}</p>`,
})
export class ManualUserComponent {
userId = signal(1);
user = signal<User | undefined>(undefined);
loading = signal(false);
error = signal<unknown>(undefined);
constructor() {
effect(() => {
const id = this.userId();
this.loading.set(true);
fetch(`/api/users/${id}`)
.then((r) => r.json())
.then((u: User) => this.user.set(u))
.catch((e) => this.error.set(e))
.finally(() => this.loading.set(false));
});
}
}This works in simple cases, but it has several problems:
- Race condition. If
userIdchanges from 1 to 2 and the request for 2 finishes first, the late response for 1 overwrites it. The screen shows user 1 whileuserIdsays 2. - Stale error. The
errorsignal is never cleared when a later request succeeds. - Boilerplate. Every fetch needs the same three signals and the same wiring.
- Writes inside effects. Angular discourages setting signals in effects because it hides data flow, and newer versions require an explicit opt-in for it.
A resource packages the correct version of this pattern once.
What a resource is
A resource is an object that does three things:
- It reads signals in a params function. These are the inputs of the request.
- It runs an asynchronous loader whenever those inputs change.
- It exposes the outcome as signals: the value, the status, and any error.
Angular provides the generic resource() function for any async source. Here it wraps fetch:
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-resource',
template: `
<button (click)="userId.set(userId() + 1)">Next user</button>
@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 UserResourceComponent {
userId = signal(1);
user = resource({
params: () => this.userId(),
loader: async ({ params: id, abortSignal }) => {
const response = await fetch(`/api/users/${id}`, { signal: abortSignal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return (await response.json()) as User;
},
});
}Points to note:
paramsreadsuserId(), so the resource tracks that signal. WhenuserIdchanges, the loader runs again.- The loader receives the value that
paramsreturned, plus anabortSignal. Passing the abort signal tofetchlets Angular cancel a request that is no longer needed. - Throwing inside the loader, or rejecting its promise, moves the resource to its error state. You do not catch the error to store it yourself.
- In Angular 19 the
paramsoption was calledrequest. Check your installed version if the option name is rejected.
The shape of a resource
Every resource exposes the same signals, whatever the data source:
| Member | Type | Meaning | Column |
|---|---|---|---|
| `value()` | `T \ | undefined` | The latest value, or `undefined` if there is none. |
| `status()` | status string | The current state of the resource. | |
| `error()` | `unknown` | The error from the last failed load, otherwise `undefined`. | |
| `isLoading()` | `boolean` | `true` while a load or reload is running. | |
| `hasValue()` | `boolean` | `true` when `value()` holds a value. Narrows the type of `value()`. | |
| `reload()` | method | Runs the loader again with the same params. | |
| `set()` and `update()` | methods | Replace the value locally without calling the loader. |
All of the reading members are signals, so templates and computed functions that read them update automatically.
The status lifecycle
The status() signal takes one of six values:
| Status | Meaning |
|---|---|
| `idle` | No valid params, so nothing is loading and there is no value. |
| `loading` | The loader is running for the first time or for new params. |
| `reloading` | The loader is running because of `reload()`. The previous value is still available. |
| `resolved` | The loader finished and `value()` holds its result. |
| `error` | The loader failed. `error()` holds the cause. |
| `local` | The value was set locally with `set()` or `update()`. |
The distinction between loading and reloading matters for the user interface. During reloading the old value is still present, so you can keep showing it and add a small spinner. During loading there is usually nothing to show yet.
How a resource avoids the race
The race in the manual version came from nobody owning the question "which request is current?" A resource owns it. When the params change while a load is in progress, the resource:
- Aborts the old load by triggering its
abortSignal. - Starts a new load with the new params.
- Ignores any result that arrives from the old load.
Two caveats apply:
- Aborting only stops the network request if your loader passes
abortSignalto the API it calls. A loader that ignores the signal still has its result discarded, but the request is not cancelled. - Changes to params are batched by signal scheduling. Setting a signal three times in one tick starts one load, not three.
Where httpResource fits
resource() knows nothing about HTTP. You must call fetch yourself, check response.ok, parse the body, and pass the abort signal along. Angular built httpResource on top of it for the very common case of reading data over HTTP. Compared with resource(), httpResource:
- Takes a URL or request object from a function that reads signals, instead of a params function plus a loader.
- Sends the request through
HttpClient, so your interceptors (authentication headers, logging, error handling) apply. - Turns non-successful HTTP statuses into the error state without extra code.
- Cancels outdated requests for you.
The result has the same members as the table above: value, status, error, isLoading, hasValue, and reload. Once you understand a resource, you understand the output side of httpResource.
When a resource is the wrong tool
Resources model reading: data that depends on inputs and can be fetched again at any time. They are a poor fit for the following:
- Writes. A POST, PATCH or DELETE is an action that should happen once, on demand. Re-running it because a signal changed would be a bug. A later chapter covers this boundary.
- Streams. Data that pushes many values over time, such as WebSockets, fits RxJS observables better than a single-value resource.
- Shared, cached server state. A resource does not deduplicate requests across components or keep a cache. Two components with the same resource send two requests.
Summary of the mental model
- A signal holds a value. A resource holds a value, a status and an error, all as signals.
- The params function declares the inputs. The loader turns them into data.
- When inputs change, the resource cancels or ignores the old load and starts a new one.
httpResourceis the same model specialized for HTTP throughHttpClient.
Exercise
A component uses an effect that calls fetch whenever a searchTerm signal changes and writes the response into a results signal. A user types "ab" and then "abc" quickly, and the results on screen sometimes belong to "ab". Explain the cause, and say what a resource does differently.
Show answer
The two requests run independently, and nothing records which one is current. If the request for "ab" finishes after the request for "abc", its callback runs last and overwrites results with stale data. A resource tracks the current load. When searchTerm changes, it aborts the old load through the abortSignal and ignores any result that still arrives from it, so only the response for "abc" can reach value().
Exercise
A resource for a user profile has status() equal to reloading. What does value() contain, and how does that differ from loading?
Show answer
During reloading, value() still holds the previously loaded profile, because reload() refreshes the same params. During loading, the params are new or it is the first load, so there is normally no value for them yet. This lets you keep the old profile visible while a reload runs.