javascript / expert
Snippet
Declarative Async State Management with the resource() API
The experimental resource() API in Angular 19+ introduces a declarative way to handle asynchronous data fetching. It automatically tracks dependencies (like userId), handles request cancellation via abortSignal, and exposes reactive status states (idle, loading, resolved, error) directly as signals, eliminating manual RxJS orchestration for simple fetch patterns.
snippet.js
javascript
1
2
3
4
5
6
7
userData = resource({request: () => ({ id: this.userId() }),loader: async ({ request, abortSignal }) => {const res = await fetch(`/api/users/${request.id}`, { signal: abortSignal });return res.json();}});
angular
Breakdown
1
request: () => ({ id: this.userId() })
Defines the reactive trigger for the resource; whenever userId changes, the loader re-runs.
2
loader: async ({ request, abortSignal }) => ...
The asynchronous function responsible for data retrieval, receiving the current request and a cancellation signal.