Sub topic 3
Updating Data Locally with Angular Resources
Assume you know TypeScript, Angular templates, signals, async/await, HttpClient, and RxJS Observables. This chapter focuses on changing resource state after it loads.
Updating data locally with `set` and `update`
A resource can change its current value without immediately making a request. Use set when you have the complete replacement value. Use update when the new value depends on the old value.
addTodo() {
this.todos.update((items) => [
...items,
{ id: crypto.randomUUID(), title: 'Draft todo' },
]);
}
replaceTodos(items: Todo[]) {
this.todos.set(items);
}These are local writes. A later reload() or parameter change can replace them with server data. Treat the server as the source of truth when persistence matters.
Using Observables with `rxResource`
Use rxResource when the data source already returns an Observable, such as an HttpClient request. Its params function follows the same reactive model as resource.
readonly user = rxResource({
params: () => ({ id: this.userId() }),
stream: ({ params }) => this.http.get<User>(`/api/users/${params.id}`),
});The stream is recreated when the parameters change. Existing RxJS cancellation and transformation operators can remain in the stream function.
Declarative HTTP with `httpResource`
httpResource is a shorter option for HTTP requests. Give it a reactive request, such as a URL derived from a signal.
readonly user = httpResource<User>(
() => `/api/users/${this.userId()}`,
);Choose resource for general asynchronous work, rxResource for Observable-based work, and httpResource for direct HTTP requests.
Chaining dependent resources
Return undefined from params until the input resource has a value. The dependent loader then stays idle instead of sending an invalid request.
readonly posts = resource({
params: () => this.user.hasValue()
? { userId: this.user.value().id }
: undefined,
loader: ({ params }) =>
fetch(`/api/users/${params.userId}/posts`).then((r) => r.json()),
});Testing components that use resources
Test the observable result, not private implementation details. Mock fetch, HttpClient, or the loader's dependency. Wait for the asynchronous work to settle, then assert value(), error(), and status signals. Also test parameter changes, failed requests, reloads, and dependent resources that begin with undefined.
Experimental status and version differences
Confirm whether resource, rxResource, and httpResource are stable in your installed Angular version. Check their imports, status names, and testing behavior. Do not assume examples from another Angular release compile unchanged.
Exercise
Which method should you use to append an item to an existing resource value?
Show answer
Use update(), because it receives the current value and returns the changed value.