Sub topic 13
Chaining dependent resources
This chapter assumes you can write a basic resource() with a params function and a loader. It also assumes you know signals (signal, computed), how abortSignal cancels a stale request, and how to read status(), value(), and error(). Chaining builds on those pieces.
The problem: the second request needs the first answer
Some data cannot be requested until other data has arrived. To load a user's posts you may first need the user, because the posts URL uses an ID, a token, or a slug that only the user response provides.
With hand-written state this is awkward. You subscribe to the first call, start the second inside the callback, and track two loading flags and two error fields. You also have to cancel the second call if the first one is superseded. A resource handles this through params.
The rule: `undefined` means "not ready"
A resource re-runs its loader when the signals read inside params change. One return value has a special meaning: if params returns undefined, the loader does not run. The resource stays in the idle state, and value() is undefined unless you set a defaultValue.
Only undefined counts as "not ready". The values null, 0, '', and false are valid params and start a load. If your input is an ID that can legitimately be 0, return the ID itself and don't write params: () => id() || undefined.
This gives a pattern. The second resource reads the first resource's signals inside its params function and returns undefined until the data it needs exists.
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
interface Post {
id: number;
title: string;
}
@Component({
selector: 'app-user-posts',
template: `<p>{{ posts.value()?.length ?? 0 }} posts</p>`,
})
export class UserPostsComponent {
readonly userId = signal(1);
readonly 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;
},
});
readonly posts = resource({
params: () => (this.user.hasValue() ? { userId: this.user.value().id } : undefined),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.userId}/posts`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Post[];
},
});
}Here is what happens when the component is created:
userstarts loading becauseuserId()has a value.postsevaluates itsparams.user.hasValue()isfalse, soparamsreturnsundefinedandpostsstaysidle.- The user response arrives and
user.value()changes.paramsofpostsread that signal, so it re-evaluates and now returns{ userId: 1 }. postsstarts loading.
No glue code connects the two. The dependency exists only because posts.params reads user's signals.
Why `hasValue()` and not `value()?.id`
You could write params: () => this.user.value()?.id and it would often work. The hasValue() check is safer for two reasons.
- In Angular 20, reading
value()while the resource is in theerrorstate throws. Aparamsfunction that reads it blindly can throw inside a computed, which surfaces as an error far from the cause.hasValue()returnsfalsein that state, so the chain simply stays idle. hasValue()narrows the type in TypeScript. After the check,this.user.value()isUserand notUser | undefined, so you don't need?.or!.
If you set a defaultValue on the upstream resource, value() is always defined and hasValue() is true even before the first load. That would start the downstream load with the placeholder. Don't give the upstream resource a default when a downstream resource uses it as a gate. Alternatively, gate on status() instead, for example this.user.status() === 'resolved'.
What happens when the upstream input changes
Suppose userId changes from 1 to 2. This sequence follows from the documented status semantics:
usersees new params and starts a load for the new user. Its in-flight request for user 1, if any, is aborted throughabortSignal.- While
userloads for new params, it has no value for them, sohasValue()isfalse. posts.paramsre-evaluates and returnsundefined. Thepostsresource goes back toidle, and its in-flight request for the old user is aborted.- When user 2 arrives,
postsloads for user 2.
This is the main benefit of the pattern. The posts of user 1 cannot be shown next to user 2, and a late response for user 1 cannot overwrite newer data. Cancellation and ordering come from the same mechanism as in a single resource.
Check the behavior of value() during loading against the Angular version you use. This part of the API changed between releases, and the exact wording is in the status documentation for your version.
Showing the combined state in the template
Each resource has its own status, so the template must decide how to combine them. The idle state of posts is ambiguous on its own. It can mean "waiting for the user" or "the user failed". Look at the upstream resource first.
import { Component, computed, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
interface Post {
id: number;
title: string;
}
@Component({
selector: 'app-user-page',
template: `
@if (error()) {
<p>Something went wrong: {{ error()?.message }}</p>
<button (click)="retry()">Retry</button>
} @else if (isLoading()) {
<p>Loading...</p>
} @else if (user.hasValue()) {
<h2>{{ user.value().name }}</h2>
<ul>
@for (post of posts.value() ?? []; track post.id) {
<li>{{ post.title }}</li>
}
</ul>
}
`,
})
export class UserPageComponent {
readonly userId = signal(1);
readonly 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;
},
});
readonly posts = resource({
params: () => (this.user.hasValue() ? { userId: this.user.value().id } : undefined),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.userId}/posts`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Post[];
},
});
readonly error = computed(() => this.user.error() ?? this.posts.error());
readonly isLoading = computed(() => this.user.isLoading() || this.posts.isLoading());
retry() {
if (this.user.error()) {
this.user.reload();
} else {
this.posts.reload();
}
}
}Two details matter here. First, error() returns the first failure in the chain. When user fails, posts never starts, so its own error is undefined. Second, retry() reloads the resource that actually failed. Reloading posts while user is in the error state does nothing useful, because posts has no params.
Status of the pair
| `user` status | `posts` status | Meaning |
|---|---|---|
| `loading` | `idle` | Waiting for the user |
| `resolved` | `loading` | User is known, loading posts |
| `resolved` | `resolved` | Everything is ready |
| `error` | `idle` | The user request failed, so posts never started |
| `resolved` | `error` | Posts failed, but the user is still valid and can be shown |
The last row is a design choice. You may prefer to show the user and an error message only for the posts section instead of replacing the whole page, as the template above does for simplicity.
Choosing between chaining and parallel loading
Chaining creates a waterfall: the second request cannot start before the first finishes, so the total time is the sum of both. Use it only when the second request really needs data from the first.
If both requests depend only on userId, create two independent resources that read userId directly. They then run in parallel.
readonly user = resource({
params: () => ({ id: this.userId() }),
loader: ({ params, abortSignal }) => this.fetchUser(params.id, abortSignal),
});
readonly posts = resource({
params: () => ({ userId: this.userId() }),
loader: ({ params, abortSignal }) => this.fetchPosts(params.userId, abortSignal),
});Here fetchUser and fetchPosts are your own methods. In the earlier examples, the posts URL could be built from userId alone, so a real application would probably load in parallel. Chaining is the right choice when the upstream response supplies something such as a resolved slug, a tenant ID, or a pagination cursor.
The same pattern in `rxResource` and `httpResource`
The undefined rule applies to the other two resource types as well.
rxResourceskips thestreamfunction whenparamsreturnsundefined.httpResourceskips the request when its reactive request function returnsundefined.
For httpResource, the dependency is therefore a one-liner:
readonly posts = httpResource<Post[]>(() => {
return this.user.hasValue() ? `/api/users/${this.user.value().id}/posts` : undefined;
});Common mistakes
- Starting the downstream load with placeholder data. Giving the upstream resource a
defaultValuemakeshasValue()true at once, so the downstream request fires with the placeholder. - Returning
nullto mean "not ready". Onlyundefinedskips the loader. Anullvalue starts a request. - Reading
value()unguarded inparams. It can throw while the upstream resource is in theerrorstate. - Showing a spinner forever. An idle downstream resource is not loading. If you derive "loading" only from the downstream resource, the page looks blank while the upstream request runs, and nothing explains an upstream error. Combine both resources as shown above.
- Chaining requests that could run in parallel. This only adds latency.
Exercise
A page loads order from /api/orders/{orderId}, and then loads customer from /api/customers/{customerId}, where customerId is a field of the order response. Write the params function of the customer resource. Then say what the customer status is while the order is still loading, and what it is if the order request fails.
Show answer
params: () => (this.order.hasValue() ? { id: this.order.value().customerId } : undefined). While the order loads, params returns undefined, so customer is idle and its loader does not run. If the order request fails, hasValue() is false, params still returns undefined, and customer stays idle. The only error in the chain is order.error(), so the template must read that one to show the failure.
Exercise
You give the upstream user resource defaultValue: { id: 0, name: '' } and keep the gate this.user.hasValue() in the posts params. What goes wrong, and how do you fix it?
Show answer
hasValue() is true from the start because the default counts as a value. posts immediately requests /api/users/0/posts, and it requests posts again once the real user arrives. Fix it by removing the defaultValue from user, or by gating on the status, for example this.user.status() === 'resolved' ? { userId: this.user.value().id } : undefined.