Sub topic 8
Loading data with rxMethod and tapResponse
This chapter assumes you know Angular signals, basic RxJS (pipe, switchMap) and the withState, patchState and withMethods pieces from earlier chapters. Here you will add asynchronous loading to a store.
Why plain methods are not enough
A method created with withMethods can call HttpClient and subscribe by hand. That approach has three problems:
- You must unsubscribe yourself.
- You must cancel stale requests yourself.
- You must handle errors yourself.
rxMethod solves this by letting you describe the work as an RxJS pipeline. The pipeline lives as long as the store does.
What rxMethod does
rxMethod<T>(pipeline) returns a function. You call it with one of three kinds of input:
- A plain value, which pushes one value into the pipeline.
- An observable, which feeds every emission into the pipeline.
- A signal, which pushes the current value now and again each time the signal changes.
The signal form is the useful one. The store reruns the request when the state changes, and you never write a subscription.
rxMethod must run in an injection context, for example inside withMethods, withHooks or a constructor. The subscription is cleaned up automatically when that context is destroyed.
A complete loading example
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';
import { tapResponse } from '@ngrx/operators';
import { patchState, signalStore, withHooks, withMethods, withState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap } from 'rxjs';
type User = { id: number; name: string };
type UsersState = { users: User[]; query: string; loading: boolean; error: string | null };
export const UsersStore = signalStore(
withState<UsersState>({ users: [], query: '', loading: false, error: null }),
withMethods((store, http = inject(HttpClient)) => ({
setQuery(query: string): void {
patchState(store, { query });
},
loadByQuery: rxMethod<string>(
pipe(
tap(() => patchState(store, { loading: true, error: null })),
switchMap((query) =>
http.get<User[]>('/api/users', { params: { q: query } }).pipe(
tapResponse({
next: (users) => patchState(store, { users, loading: false }),
error: (err: Error) => patchState(store, { loading: false, error: err.message }),
}),
),
),
),
),
})),
withHooks({
onInit(store) {
store.loadByQuery(store.query);
},
}),
);The pipeline has three steps:
tapsetsloadingto true and clears the previous error.switchMapstarts the HTTP request. If a new query arrives first,switchMapcancels the earlier request, so a slow response cannot overwrite a newer one.tapResponsewrites the result or the error into state.
The onInit hook passes store.query, which is a signal, to loadByQuery. From then on, calling setQuery('ann') changes the signal and triggers a new request.
Why tapResponse goes inside switchMap
tapResponse comes from @ngrx/operators. It takes next and error handlers, and it catches the error so the stream completes normally instead of failing.
Placement matters. An error that reaches the outer pipeline terminates it, and later signal changes would then do nothing. Putting tapResponse on the inner request means only that one request ends. The outer pipeline stays alive for the next query.
Common errors
- Calling
rxMethodoutside an injection context. Angular throws an error. Call it insidewithMethodsorwithHooks, or pass aninjectoroption. - Passing
store.query()instead ofstore.query. Calling the signal sends one fixed value. Pass the signal itself to get reruns. - Using
mergeMapfor search-style requests. Responses can arrive out of order. UseswitchMapwhen only the latest result matters, andconcatMaporexhaustMapwhen requests must not be dropped or must not overlap. - Mutating state in
next. Always go throughpatchState.
Exercise
In the example, a user types "a", then "an" before the first request finishes. What happens to the first request, and why does the store keep working if the second request fails?
Show answer
switchMap cancels the first request when the second query arrives, so only the response for "an" can update state. If the second request fails, tapResponse catches the error on the inner observable and writes it to error. The outer pipeline stays subscribed, so later query changes still trigger requests.