Sub topic 14
Loading Async Data with resource() (Experimental)
This chapter assumes you already know writable signals, computed(), and linkedSignal(), plus the toSignal() and toObservable() bridge from the RxJS chapter. It also assumes you can make HTTP calls with HttpClient or fetch.
The resource() API is experimental. Its names have changed between versions. This chapter uses the Angular 20+ shape, where the reactive input is called params. In Angular 19 the same option was called request.
The Problem resource() Solves
In the previous chapter, a search box used toObservable, switchMap, and toSignal to turn a signal into HTTP results. That pattern works, but you must handle the loading flag, errors, and cancellation yourself. A resource wraps all of this up. You give it a reactive input and an async loader. It gives back signals for the value, the status, and any error.
The Working Model
A resource has two parts:
paramsis a reactive function, like acomputed(). Each time a signal it reads changes, the resource runs the loader again.loaderis an async function that receives the currentparamsand anabortSignal. When new params arrive before the old request finishes, Angular aborts the old request. This gives you the same cancellation thatswitchMapdoes.
A resource() Example
import { Component, resource, signal } from '@angular/core';
interface User { id: number; name: string; }
@Component({
selector: 'app-user-card',
template: `
<button (click)="userId.update(id => id + 1)">Next user</button>
@if (user.isLoading()) {
<p>Loading...</p>
} @else if (user.error()) {
<p>Could not load user.</p>
<button (click)="user.reload()">Retry</button>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
}
`,
})
export class UserCardComponent {
userId = signal(1);
user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as User;
},
});
}When userId changes, params produces a new object, and the loader runs again. Note that isLoading() is true in both the loading and reloading states.
Status Values
| Status | Meaning |
|---|---|
| `idle` | `params` returned `undefined`, so the loader has not run |
| `loading` | Loader is running for new params |
| `reloading` | Loader is running after `reload()`, and the previous value is still available |
| `resolved` | Loader finished successfully |
| `error` | Loader threw or rejected |
| `local` | You overwrote the value with `value.set()` or `value.update()` |
If params returns undefined, the resource stays idle and the loader does not run. This lets you skip loading until an input is ready, for example params: () => this.id() ?? undefined.
httpResource() for HttpClient
For plain GET requests, httpResource() from @angular/common/http is shorter. It uses HttpClient, so interceptors apply, and it requires provideHttpClient().
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User { id: number; name: string; }
@Component({
selector: 'app-user-name',
template: `
@if (user.hasValue()) {
<p>{{ user.value().name }}</p>
}
`,
})
export class UserNameComponent {
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`);
}The URL function works like params: when userId changes, it sends a new request. If the function returns undefined, no request is sent.
Common Errors
- Reading a signal inside
loaderand expecting it to trigger reloads. Only signals read inparamsare tracked. Pass everything the loader needs throughparams. - Forgetting to pass
abortSignaltofetch. If you do, stale responses still download, though the resource ignores them. - Using a resource for mutations. Resources are meant for reading data. Send POST and PUT requests through a service method.
- Relying on the API being stable. Pin your Angular version and check the release notes when you upgrade.
Exercise
A component has filter = signal('') and page = signal(1). Its resource uses params: () => ({ filter: this.filter() }), and the loader reads this.page() to build the URL. Changing the page does not reload data. Why, and how do you fix it?
Show answer
Only signals read in params are tracked, and the loader runs untracked. Move page into params: params: () => ({ filter: this.filter(), page: this.page() }), and read params.page in the loader.
Exercise
You want a resource to load nothing until the user picks an id from selectedId = signal<number | null>(null). What should params return?
Show answer
Return undefined when no id is selected, for example params: () => this.selectedId() ?? undefined. The resource stays idle and the loader does not run.