Sub topic 14
Loading Async Data with resource() (Experimental)
Every signal so far in this tutorial has been synchronous. computed() derives a value right away, and linkedSignal() resets right away when its source changes. Real applications also need data that arrives later, such as an HTTP response. Angular's resource() API connects async work to the signal graph. You describe which signals the request depends on, and Angular reruns the request whenever those signals change. It exposes the result, the loading state and any error as signals.
This chapter assumes you know signal(), computed() and effect() from earlier chapters, and that you have used fetch or HttpClient. The RxJS section assumes you have read the chapter on toSignal() and toObservable().
Why Not Just Use an effect()?
You could load data with an effect that watches an id signal, calls fetch, and writes the result into another signal. That approach has gaps you must fill by hand:
- Responses can arrive out of order. If the id changes twice quickly, the older response may land last and overwrite the newer one.
- Nothing cancels the stale request.
- You need separate signals for loading and error state, and you must keep them in sync.
- Writing signals inside effects is a pattern the earlier chapter warned against, because it hides data flow.
resource() handles all of this. It aborts stale requests, ignores results that are out of date, and tracks status for you.
The Shape of a Resource
A resource has two parts:
paramsis a reactive function, like the body of acomputed(). Angular tracks every signal it reads. When any of them changes, the resource loads again.loaderis an async function that receives the current params and returns a Promise of the value. The loader is not tracked. Signals read inside it do not trigger reloads.
Here is a complete component that loads a user by id:
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
email: string;
}
@Component({
selector: 'app-user-detail',
template: `
<button (click)="prev()">Previous</button>
<button (click)="next()">Next</button>
@if (user.isLoading()) {
<p>Loading user {{ userId() }}...</p>
}
@if (user.error()) {
<p>Could not load user: {{ user.error() }}</p>
}
@if (user.hasValue()) {
<h2>{{ user.value()?.name }}</h2>
<p>{{ user.value()?.email }}</p>
}
`,
})
export class UserDetailComponent {
userId = signal(1);
user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(
`https://jsonplaceholder.typicode.com/users/${params.id}`,
{ signal: abortSignal }
);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return (await res.json()) as User;
},
});
next() {
this.userId.update(id => id + 1);
}
prev() {
this.userId.update(id => Math.max(1, id - 1));
}
}Click "Next" three times quickly. Each click changes userId, which changes params, so Angular calls the loader again. Before each new call it fires abortSignal for the previous call. Because the code passes abortSignal to fetch, the browser cancels the old requests. If you forget to pass it, the old requests still finish, but Angular throws away their results. Only the latest params can set value.
Like effect(), resource() must be created in an injection context, such as a field initializer or the constructor. Angular destroys it, and aborts any pending load, when the component is destroyed.
Reading Resource State
A resource exposes these members:
| Member | Type | Meaning |
|---|---|---|
| `value()` | signal | The latest loaded value, or `undefined` (or the default value) before the first load |
| `status()` | signal | One of `'idle'`, `'loading'`, `'reloading'`, `'resolved'`, `'error'`, `'local'` |
| `error()` | signal | The thrown error when status is `'error'`, otherwise `undefined` |
| `isLoading()` | signal | `true` while status is `'loading'` or `'reloading'` |
| `hasValue()` | method | `true` when a usable value is available |
| `reload()` | method | Calls the loader again with the same params |
| `set()` / `update()` | methods | Overwrite the value locally (status becomes `'local'`) |
The statuses move like this:
The difference between 'loading' and 'reloading' matters for UI. On reload() the resource keeps its current value while it fetches again. So you can show a small spinner next to the existing data instead of blanking the screen. When params change, the status goes to 'loading' and the value resets, because the old value belongs to different params.
A safe derived signal looks like this:
userName = computed(() =>
this.user.hasValue() ? this.user.value()?.name ?? '' : ''
);Skipping Loads with undefined Params
If params returns undefined, the resource goes to 'idle' and does not call the loader. Use this for conditional loading, such as a search box that should not request anything until the user types:
import { Component, resource, signal } from '@angular/core';
@Component({
selector: 'app-book-search',
template: `
<input
[value]="query()"
(input)="query.set($any($event.target).value)"
placeholder="Search books"
/>
<button (click)="books.reload()" [disabled]="!query()">Refresh</button>
<p>Status: {{ books.status() }}</p>
@for (title of books.value(); track title) {
<p>{{ title }}</p>
}
`,
})
export class BookSearchComponent {
query = signal('');
books = resource({
params: () => {
const q = this.query().trim();
return q.length >= 2 ? { q } : undefined;
},
defaultValue: [] as string[],
loader: async ({ params, abortSignal }) => {
const res = await fetch(
`https://openlibrary.org/search.json?q=${encodeURIComponent(params.q)}&limit=5`,
{ signal: abortSignal }
);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const body = (await res.json()) as { docs: { title: string }[] };
return body.docs.map(d => d.title);
},
});
}defaultValue replaces undefined as the value when the resource is idle, loading or failed, so @for always gets an array. Inside the loader, TypeScript knows params is not undefined, because Angular never calls the loader in that case.
This example does not debounce. Each keystroke past two characters starts a request and aborts the previous one. That is acceptable for many cases, but resource() has no built-in debounce. If you need one, debounce the source signal with RxJS (toObservable plus debounceTime, then toSignal) and read that debounced signal in params.
Local Updates and Optimistic UI
A resource is writable. set() and update() replace the value and change the status to 'local'. This works for optimistic updates: show the change at once, then save it to the server.
async rename(newName: string) {
const before = this.user.value();
this.user.update(u => (u ? { ...u, name: newName } : u));
try {
await fetch(`/api/users/${this.userId()}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName }),
});
} catch {
this.user.set(before);
}
}The local value lasts until params change or you call reload(). Then server data replaces it.
httpResource(): Resources Backed by HttpClient
Most Angular apps use HttpClient rather than fetch, so that interceptors handle auth headers, logging and error mapping. httpResource() (from @angular/common/http) builds a resource on top of HttpClient. You give it a reactive function that returns a URL or a request object. Returning undefined skips the request, the same as with params.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Todo {
id: number;
title: string;
completed: boolean;
}
@Component({
selector: 'app-todos',
template: `
<label>
<input type="checkbox" (change)="onlyOpen.set($any($event.target).checked)" />
Only open
</label>
@if (todos.isLoading()) {
<p>Loading...</p>
}
@for (todo of todos.value(); track todo.id) {
<p>{{ todo.title }}</p>
}
`,
})
export class TodosComponent {
onlyOpen = signal(false);
todos = httpResource<Todo[]>(
() => ({
url: 'https://jsonplaceholder.typicode.com/todos',
params: this.onlyOpen() ? { completed: 'false', _limit: '10' } : { _limit: '10' },
}),
{ defaultValue: [] }
);
}The application must provide HttpClient with provideHttpClient() in its config. Besides the usual resource members, httpResource adds headers(), statusCode() and progress() signals. Variants such as httpResource.text() and httpResource.blob() handle non-JSON responses. The parse option lets you check the response at runtime, for example with a schema library, instead of trusting the generic type.
rxResource(): When the Loader Is an Observable
If you already have services that return Observables, rxResource() from @angular/core/rxjs-interop accepts a stream function that returns an Observable instead of a Promise. Angular unsubscribes from the previous Observable when params change.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { rxResource } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-post',
template: `<h3>{{ post.value()?.title }}</h3>`,
})
export class PostComponent {
private http = inject(HttpClient);
postId = signal(1);
post = rxResource({
params: () => ({ id: this.postId() }),
stream: ({ params }) =>
this.http.get<{ title: string }>(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
),
});
}In Angular 19, this option was called loader, not stream.
Choosing Between the Options
| Situation | Use |
|---|---|
| Plain GET that should go through interceptors | `httpResource()` |
| Non-HTTP async work, or a third-party SDK returning Promises | `resource()` |
| Existing Observable-based services or streaming values | `rxResource()` |
| Complex stream logic (debounce, retry, combine) | RxJS pipeline plus `toSignal()` |
| Mutations | Direct `HttpClient` calls, then `reload()` or `set()` |
Common Mistakes
- Reading signals in the loader and expecting reloads. The loader is untracked. Every reactive dependency belongs in
params. - Ignoring
abortSignal. Results stay correct, but stale requests still use bandwidth and server time. Pass it tofetch. - Reading
value()without a guard. In the error state this throws in recent versions. UsehasValue()ordefaultValue. - Creating a resource outside an injection context. Calling
resource()inside a click handler fails. Create it once as a field and drive it with signals. - Returning a new object from
paramson every run without real changes. This is harmless, because Angular only rerunsparamswhen a tracked signal changes. But if you compute params from a signal that changes often, each change reloads. Add a customequalto the source signal if needed. - Relying on the exact API in production. The API is experimental. Wrap resources in a service or small helper so a future rename touches one file.
Exercise
A component has page = signal(1) and pageSize = signal(20). Its loader reads this.pageSize() directly inside the async function, while params returns { page: this.page() }. What happens when the user changes the page size, and how do you fix it?
Show answer
Nothing reloads. The loader is untracked, so pageSize is not a dependency of the resource. The list keeps the old size until page changes. Fix it by moving the read into params: params: () => ({ page: this.page(), size: this.pageSize() }), then use params.size in the loader.
Exercise
You show a product list from a resource and add a "Refresh" button that calls reload(). Users complain that the list flashes empty when they refresh. They report the same flash when they change the category filter. Which of these is expected, and what template change removes the flash on refresh?
Show answer
The flash on category change is expected. New params move the status to 'loading', and the old value belongs to the old category. On reload() the status is 'reloading' and the value is kept, so the refresh flash comes from the template hiding the list whenever isLoading() is true. Render the list whenever hasValue() is true, and show a small indicator when status() === 'reloading' instead of replacing the list.
Exercise
Write the params function for an httpResource that loads /api/orders/{id} only when a signal orderId (type number | null) holds a number.
Show answer
httpResource<Order>(() => { const id = this.orderId(); return id === null ? undefined : /api/orders/${id}; }). Returning undefined keeps the resource idle and sends no request while orderId is null.