0 day streak
javascript / expert
Snippet

Declarative Data Fetching with the Resource API

The Resource API (introduced in Angular 19) provides a declarative way to handle asynchronous data fetching as a signal. It automatically manages loading states, errors, and cancellation (via abortSignal) while reacting to upstream signal changes in the 'request' parameter.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { resource, signal } from '@angular/core';
export class UserProfile {
userId = signal(123);
userResource = resource({
request: () => ({ id: this.userId() }),
loader: async ({ request, abortSignal }) => {
const resp = await fetch(`https://api.example.com/users/${request.id}`, { signal: abortSignal });
if (!resp.ok) throw new Error('Fetch failed');
return await resp.json();
}
});
updateUser() {
// Changing the signal automatically triggers a new loader execution
this.userId.set(456);
}
}
angular
Breakdown
1
request: () => ({ id: this.userId() })
Defines the reactive dependencies; the loader re-runs whenever userId changes.
2
loader: async ({ request, abortSignal }) => { ... }
The asynchronous function that fetches data, receiving the request payload and an abort token.
3
userResource = resource({ ... })
Creates a ResourceRef containing signals for value, status, and error.