Load data with resource in Angular
Fetch async data tied to a signal with Angular's experimental resource API, and read its value, status and error without writing the plumbing.
Loading data when an id changes usually means an effect, a loading flag and manual cancellation. resource ties an async loader to signals.
import { Component, resource, signal } from '@angular/core';
@Component({
selector: 'app-user',
template: `
<button (click)="id.set(id() + 1)">Next</button>
@if (user.isLoading()) {
<p>Loading…</p>
} @else if (user.error()) {
<p>Could not load the user</p>
} @else {
<p>{{ user.value()?.name }}</p>
}
`,
})
export class UserComponent {
id = signal(1);
user = resource({
params: () => ({ id: this.id() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error('Request failed');
return res.json();
},
});
}Loading…
Ada (id 1)
Loading… (after Next)
Lin (id 2)When params changes, the previous request is aborted through abortSignal and the loader runs again. The params and loader option names are those of Angular 20 and later, where the feature is still experimental, so its API may change. See Async reactivity with resources.
For plain HTTP calls through HttpClient, httpResource is the more convenient sibling. Treat both as experimental before relying on them in a production application.