Sub topic 11
Using Observables with rxResource
This chapter assumes you know the following:
- How a plain
resource()works:params,loader, and thevalue,status, anderrorsignals. - The basics of RxJS:
Observable,pipe,switchMap. - How
HttpClientreturns cold Observables.
rxResource is the version of resource for code that already produces Observables. You will see how it differs from resource, what happens to the subscription, and where the edge cases are.
What rxResource is
rxResource lives in a separate entry point, @angular/core/rxjs-interop, so core Angular stays free of an RxJS dependency. It has the same reactive model as resource:
- A
paramsfunction reads signals. When any of them change, the resource starts a new request. - If
paramsreturnsundefined, the resource stays idle and nothing runs. - It exposes the same signals:
value,status,error,isLoading,hasValue(), plusreload(),set(), andupdate().
Only the loading function changes. Instead of an async loader that returns a Promise, you write a stream function that returns an Observable.
import { Component, inject, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-rx',
template: `
@if (user.error()) {
<p>Could not load the user.</p>
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ user.value()?.name }}</p>
}
`,
})
export class UserRxComponent {
private readonly http = inject(HttpClient);
readonly userId = signal(1);
readonly user = rxResource({
params: () => ({ id: this.userId() }),
stream: ({ params }) => this.http.get<User>(`/api/users/${params.id}`),
});
}The application must provide HttpClient, for example with provideHttpClient() in the application config. Like resource, rxResource must be created in an injection context. A field initializer in a component, as above, qualifies. Elsewhere, pass an injector option.
Cancellation by unsubscribing
With resource you pass abortSignal to fetch by hand. With rxResource you do nothing. The resource subscribes to the Observable and unsubscribes when the request is superseded. HttpClient cancels the underlying request when its subscriber leaves, so stale requests are aborted automatically.
The resource unsubscribes in three cases:
- A signal read in
paramschanges while a request is running. reload()is called while a request is running.- The owning component or service is destroyed.
Putting RxJS operators to work
The main reason to choose rxResource is to reuse operators that Promises lack. The next example debounces a search box inside the stream.
import { Component, inject, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { switchMap, timer } from 'rxjs';
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" />
@if (results.isLoading()) {
<p>Searching...</p>
}
<ul>
@for (item of results.value() ?? []; track item) {
<li>{{ item }}</li>
}
</ul>
`,
})
export class SearchComponent {
private readonly http = inject(HttpClient);
readonly query = signal('');
readonly results = rxResource({
params: () => {
const q = this.query().trim();
return q ? { q } : undefined;
},
stream: ({ params }) =>
timer(300).pipe(
switchMap(() => this.http.get<string[]>('/api/search', { params: { q: params.q } })),
),
});
}Two mechanisms work together here:
timer(300)delays the request by 300 ms. If the user types again,paramschanges, the resource unsubscribes, and the pending timer is discarded. This gives you a debounce without a separate operator or aSubject.- An empty query makes
paramsreturnundefined. The resource goes idle, so no request is sent for an empty box.
Streams that emit more than once
A Promise settles once. An Observable can emit many times. In recent Angular versions, each emission from the stream function updates value, so a resource can show live data such as a WebSocket feed.
import { Component } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-clock',
template: `<p>Seconds since start: {{ seconds.value() }}</p>`,
})
export class ClockComponent {
readonly seconds = rxResource({
stream: () => interval(1000).pipe(map((n) => n + 1)),
});
}This is a point where versions differ. Early releases of the API used only the first emission, and the stream option was named loader. Check the documentation for your version before you rely on multiple emissions. The last section of this chapter covers other renames.
How the resource treats completion and errors
The resource reacts to the three Observable notifications as follows:
| Notification | Effect on the resource |
|---|---|
| `next` | `value` is updated and the status becomes `resolved`. |
| `error` | The status becomes `error`, and `error()` holds the thrown value. |
| `complete` | No change if a value was already emitted. |
If the Observable completes without ever emitting, recent versions put the resource into the error state, because there is no value to show. A stream such as EMPTY or a filter that drops every item causes this. If "no result" is a valid outcome, emit a sentinel instead, for example defaultIfEmpty(null).
An error does not terminate the resource permanently. The resource subscribes again when params changes or when you call reload(). You can use catchError inside the stream to turn a failure into a fallback value. In that case the resource never enters the error state. This hides the failure from the template, so use it only when a fallback is the right behaviour.
Choosing between resource and rxResource
| Situation | Better choice |
|---|---|
| The data source is `fetch` or another Promise API | `resource` |
| The source is a service method that returns an Observable | `rxResource` |
| You need interceptors, `HttpClient` testing utilities, or `HttpContext` | `rxResource`, or `httpResource` (next chapter) |
| You want to debounce, retry, or combine sources with operators | `rxResource` |
| You want the shortest code for a plain GET request | `httpResource` |
You can convert between the two styles. An Observable can become a Promise with firstValueFrom, and a Promise can become an Observable with from. Pick the one that matches your source. Converting just to use a different resource function usually adds code and removes the automatic cancellation.
Common mistakes
- Reading signals inside
stream. Only signals read inparamstrigger a new request. A signal read inside the Observable chain is untracked, so a change to it does not re-run the stream. Move it intoparamsand use theparamsargument. - Returning a hot, shared Observable and expecting cancellation. Unsubscribing from a shared stream does not stop the work behind it if other subscribers remain. Cancellation of the HTTP request only happens for cold Observables like
HttpClientcalls. - Calling
rxResourceoutside an injection context. This throws at runtime. Create it in a field initializer or constructor, or passinjector. - Missing
provideHttpClient(). Theinject(HttpClient)call fails with a missing provider error. - Using the older option names. Code copied from a blog post for another version may use
requestandloader. See the next section.
Stability and naming
The resource API is experimental in the releases that ship it, and rxResource shares that status. The option names changed between releases. Early versions used request for the reactive inputs and loader for the loading function. Later versions use params and stream for rxResource. Experimental APIs can change in minor releases, so check the Angular documentation for the exact version in your package.json. Treat the code in this chapter as written for the params/stream form.
Exercise
A search resource built with rxResource uses params: () => ({ q: this.query() }) and stream: ({ params }) => this.http.get(...). A user types "a", then quickly "ab". What happens to the request for "a", and why do you not need to pass an abort signal?
Show answer
The change to query makes params return a new value, so the resource unsubscribes from the Observable for "a". HttpClient cancels its underlying request when its subscriber unsubscribes, so the request for "a" is aborted and only "ab" can set the value. No abort signal is needed because cancellation happens through the Observable subscription.
Exercise
Your stream function returns this.http.get<Item[]>(...).pipe(filter((items) => items.length > 0)). For a query with no matches, the resource ends up in the error state. Why, and how can you fix it?
Show answer
The filter drops the only emission, so the Observable completes without producing a value. In recent versions the resource treats that as an error. Remove the filter and handle the empty array in the template, or add defaultIfEmpty([]) so the stream always emits a value.