Sub topic 3
Your first resource
This chapter builds a resource from scratch and explains what Angular does with it. It assumes you know TypeScript with async/await, Angular components and templates, and the basic signal primitives (signal, computed, effect). It also assumes you have used fetch or HttpClient before. Reactive params and cancellation get a short preview here and a full treatment in the next chapters.
What a resource is
A resource is an object that runs an asynchronous function (the loader) and publishes the outcome as signals. You don't write loading, error and data fields and update them by hand. The resource keeps them in sync with the request.
You create one with the resource() function from @angular/core. It returns a ResourceRef. The main members of a ResourceRef are all signals or methods:
| Member | Kind | Meaning |
|---|---|---|
| `value()` | signal | The latest value, or `undefined` if there is none yet |
| `status()` | signal | One of `idle`, `loading`, `reloading`, `resolved`, `error`, `local` |
| `error()` | signal | The thrown error, or `undefined` |
| `isLoading()` | signal | `true` while `status` is `loading` or `reloading` |
| `hasValue()` | signal | `true` if a value is available |
| `reload()` | method | Runs the loader again |
| `set()` / `update()` | methods | Replace the value locally |
| `destroy()` | method | Stops the resource and aborts any request in flight |
Later chapters cover most of these in detail. Here we use value, isLoading and error.
A minimal resource
The smallest useful resource has only a loader. Because it reads no signals, it runs once.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-list',
template: `
@if (todos.error()) {
<p>Could not load the todos.</p>
} @else if (todos.isLoading()) {
<p>Loading...</p>
} @else {
<ul>
@for (todo of todos.value(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
}
`,
})
export class TodoListComponent {
readonly todos = resource({
loader: async () => {
const res = await fetch('/api/todos');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
}Three things in this example matter.
- The loader returns a Promise. Anything you can
awaitworks. The type oftodos.value()is inferred from the resolved type, plusundefined. Here it isTodo[] | undefined. - A failed response must throw.
fetchonly rejects on network failure. It resolves normally for a 404 or 500. If you don't checkres.okand throw, the resource reportsresolvedwith an error body as its value. - The template reads signals. Each read of
todos.error(),todos.isLoading()ortodos.value()registers a dependency. When the loader finishes and the resource updates its signals, Angular re-renders only what changed.
When the loader runs
You never call the loader yourself. Angular schedules it. The first run does not happen synchronously inside resource(). It happens when Angular next processes pending effects, which is normally during the first change detection pass of the component. Until then, status() is loading, isLoading() is true, and value() is undefined.
This has a practical consequence. Don't read value() in the constructor and expect data. Read it in templates, computed signals or effects, which all re-run when the value arrives.
import { Component, computed, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
done: boolean;
}
@Component({
selector: 'app-todo-summary',
template: `<p>{{ summary() }}</p>`,
})
export class TodoSummaryComponent {
readonly todos = resource({
loader: async () => {
const res = await fetch('/api/todos');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
readonly summary = computed(() => {
if (!this.todos.hasValue()) return 'No data yet';
const open = this.todos.value().filter((t) => !t.done).length;
return `${open} open todos`;
});
}hasValue() narrows the type, so inside the if TypeScript knows value() is not undefined. The computed re-evaluates when the resource changes, so the text updates on its own.
The lifecycle at a glance
The diagram shows the states a first resource goes through. A resource without params starts in loading. The idle state appears when params returns undefined, which a later chapter explains.
loading means the first load, with nothing to show yet. reloading means a later load, where the previous value may still be available. That difference lets a UI keep showing old data with a spinner on top instead of blanking the screen.
Injection context and cleanup
resource() must run in an injection context. Field initializers and constructors in components, directives and services are injection contexts, so the examples above work as written. If you create a resource somewhere else, such as inside a method, pass an Injector.
import { Component, Injector, inject, resource } from '@angular/core';
@Component({
selector: 'app-lazy',
template: `<button (click)="start()">Load</button>`,
})
export class LazyComponent {
private readonly injector = inject(Injector);
start() {
const data = resource({
injector: this.injector,
loader: async () => {
const res = await fetch('/api/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
});
console.log(data.status());
}
}Without the injector option, this call would throw because start() runs outside an injection context. Be careful with this pattern. Each click creates a new resource, which is rarely what you want. Prefer one resource as a field and drive it with signals.
The injector also controls cleanup. When the owning component or service is destroyed, the resource is destroyed with it. Any request in flight is aborted and no further updates are published.
Setting a default value
Having value() be undefined before the first load forces ?. or hasValue() checks everywhere. If an empty value makes sense for your data, pass defaultValue.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-count',
template: `<p>{{ todos.value().length }} todos</p>`,
})
export class TodoCountComponent {
readonly todos = resource({
defaultValue: [] as Todo[],
loader: async () => {
const res = await fetch('/api/todos');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
}With defaultValue, the type of value() is Todo[], with no undefined. The template can read .length directly. The trade-off is that you can no longer tell "not loaded yet" from "loaded and empty" by looking at the value. Use status() or isLoading() for that distinction.
A look ahead: params
The loader above has no inputs, so it runs once. To make a resource depend on signals, you add a params function. Angular tracks the signals that function reads and re-runs the loader when they change. The loader then receives the computed params as an argument.
import { Component, resource, signal } from '@angular/core';
@Component({
selector: 'app-title',
template: `<p>{{ title.value() }}</p>`,
})
export class TitleComponent {
readonly postId = signal(1);
readonly title = resource({
params: () => ({ id: this.postId() }),
loader: async ({ params }) => {
const res = await fetch(`/api/posts/${params.id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return ((await res.json()) as { title: string }).title;
},
});
}The next chapter explains this model in full. For now, note the division of labor. params is reactive and tracked. The loader is not tracked, so signals you read inside the loader body will not trigger a reload. Put anything that should cause a reload in params.
Common mistakes
- Not throwing on bad HTTP statuses. A 500 response resolves the Promise. Check
res.okand throw. - Reading signals inside the loader and expecting a reload. The loader is untracked. Read them in
params. - Calling
resource()outside an injection context. Move it to a field initializer, or passinjector. - Treating
undefinedas "empty". Before the first load,undefinedmeans "nothing yet". UsedefaultValueorhasValue()deliberately. - Reading
value()in an error state. Recent versions can throw when you readvalue()after a failed load. Checkerror()orhasValue()first, as the first template does.
Exercise
A component declares readonly items = resource({ loader: async () => (await fetch('/api/items')).json() }). The server returns HTTP 500 with a JSON body {"message":"oops"}. What will items.status() be after the request finishes, and what single change makes the resource report the failure?
Show answer
The status will be resolved, and items.value() will hold the error body, because fetch does not reject on a 500 response. Check res.ok inside the loader and throw (for example if (!res.ok) throw new Error(HTTP ${res.status})). The loader's Promise then rejects, the status becomes error, and items.error() holds the thrown error.
Exercise
You want a template to read todos.value().length without ?. or an @if guard, and the empty list is a valid value before loading finishes. Which option do you add to the resource, and which signal do you use to tell "still loading" apart from "loaded and empty"?
Show answer
Add defaultValue: [] as Todo[]. Then value() is typed as Todo[] and is never undefined. Use isLoading() (or status()) to tell a pending load from a completed load that returned an empty list.