Sub topic 8
Loading data with rxMethod and tapResponse
Every real application loads data from a server. This chapter shows how to do that inside a SignalStore with rxMethod, which connects RxJS streams to store methods, and tapResponse, which writes results and errors into state safely.
This chapter assumes you know the following:
- How to create a store with
signalStore,withStateandwithMethods, and howpatchStateupdates state. - Angular signals and the
effectfunction. - Basic RxJS: observables,
pipe,tapandswitchMap. - Angular's
HttpClient.
The problem rxMethod solves
A store method can call HttpClient directly and subscribe to the result. That quickly causes three problems:
- Stale responses. A user types "al", then "alice". If the "al" response arrives last, it overwrites the newer result.
- Leaked subscriptions. Each manual
subscribecall needs a matching unsubscribe. - Killed streams. In an RxJS pipeline, an unhandled HTTP error ends the whole stream, so later requests never run.
rxMethod addresses the first two. It takes an RxJS operator pipeline and returns a store method. You call that method with a value, a signal or an observable. The pipeline runs for each emission, and the subscription ends when the store is destroyed. tapResponse addresses the third problem.
The full example
This store loads users that match a search query.
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 following sections go through it piece by piece.
Anatomy of rxMethod
rxMethod<string>(...) takes one argument: a function from an observable of string to another observable. pipe(...) from RxJS builds that function. The type parameter is the input type of the method you get back. Here that is string, so loadByQuery accepts a string, a Signal<string> or an Observable<string>.
The output type of the pipeline does not matter, because rxMethod subscribes and discards the values. State changes happen as side effects inside tap and tapResponse.
Two details of how rxMethod works:
- It needs an injection context. The store's
withMethodsfactory andwithHookscallbacks run in one, so the example works. Calling anrxMethodfrom a plain event handler works only if therxMethoditself was created in the store factory, as it is here. You call the method, not create it, at that point. - It returns a reference. The call returns an object with a
destroy()method. Use it to stop one specific subscription before the store is destroyed. Most code ignores it.
Three ways to call the method
| Call | What happens |
|---|---|
| `store.loadByQuery('alice')` | The pipeline runs once with `'alice'`. |
| `store.loadByQuery(someSignal)` | The pipeline runs now and again each time the signal changes. |
| `store.loadByQuery(someObservable$)` | The pipeline runs for each value the observable emits. |
The signal form is the one this example uses. In onInit, store.query is a signal, so store.loadByQuery(store.query) connects the two. Whenever setQuery changes the query, the request runs again. No component code has to call loadByQuery after a query change.
Signal inputs are read inside an effect. Angular runs effects asynchronously, so if the signal changes several times in a row, the pipeline sees only the latest value. That is a useful coalescing, and it also means the first request starts after the current change detection pass, not immediately.
Choosing the flattening operator
The pipeline decides what happens when a new value arrives while a request is still running. The choice is in the flattening operator.
| Operator | Behavior | Typical use |
|---|---|---|
| `switchMap` | Cancels the running request and starts the new one. | Search, filters, reloads. |
| `concatMap` | Queues requests and runs them one at a time, in order. | Saves that must keep their order. |
| `exhaustMap` | Ignores new values while a request runs. | Submit buttons, refresh clicks. |
| `mergeMap` | Runs all requests in parallel. | Independent items where order does not matter. |
With switchMap, unsubscribing from the old HttpClient observable aborts the browser request. The stale-response problem from the start of this chapter cannot occur, because the old request's response is never delivered.
Why tapResponse matters
Look at the structure of the pipeline. The tapResponse operator sits on the inner observable, the one returned by http.get(...), not on the outer pipeline. This placement is the main thing to get right.
An RxJS stream ends on its first error. If the HTTP error propagated to the outer pipeline, the rxMethod subscription would complete with an error. The next setQuery would then do nothing, because nothing is listening anymore. Handling the error inside the inner observable keeps the outer stream alive.
tapResponse is a small operator from @ngrx/operators. It combines tap and catchError and does this:
- It calls
nextfor each value. - It calls
errorif the inner observable fails, then completes the inner observable without re-emitting the error. - It accepts optional
completeandfinalizecallbacks.
Put it last in the inner pipe. If you place it earlier and an operator after it throws, that error is not caught.
Typing the error
The error callback receives unknown unless you annotate it. The example writes (err: Error), which lets you read err.message. For HTTP calls the actual object is an HttpErrorResponse, so you can annotate that type when you need status or the response body. Annotating does not check the value at runtime, so keep the handling simple.
Tracking loading and error state
The example keeps loading and error as plain state fields. The tap before switchMap sets loading: true and clears the old error. Both branches of tapResponse set loading: false.
The reason to clear the error in the first tap is that a new request should not show the previous request's failure. The reason to set loading before switchMap, not inside it, is that the flag turns on the moment a value arrives, including when it cancels an earlier request. The flag then stays true across the cancel and replace, which is the behavior you want.
If several stores need the same pair of fields, put them in a signalStoreFeature, which a later chapter covers.
Adding a debounce
A text input can change on every keystroke. To avoid one request per character, add debounceTime before the flattening operator. This store is complete and uses the same pattern with a debounce.
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 { debounceTime, distinctUntilChanged, filter, pipe, switchMap, tap } from 'rxjs';
type User = { id: number; name: string };
export const SearchStore = signalStore(
withState({ users: [] as User[], query: '', loading: false, error: null as string | null }),
withMethods((store, http = inject(HttpClient)) => ({
setQuery(query: string): void {
patchState(store, { query });
},
search: rxMethod<string>(
pipe(
debounceTime(300),
distinctUntilChanged(),
filter((query) => query.length >= 2),
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.search(store.query);
},
}),
);distinctUntilChanged drops repeated values, and filter skips queries that are too short. Because the loading flag is set after these operators, it does not flash on for requests that never happen.
Starting the first load
The onInit hook in the example calls loadByQuery once. Because it passes a signal, that single call also covers all later changes. If you pass a plain value instead, such as store.loadByQuery(''), you get one load and no reactions.
The call in onInit fires when the store is created. For a root-level store that happens on first injection, not at application start. A component-level store loads when its component is created.
Testing the load
The store is a normal injectable, so test it with TestBed and HttpTestingController. The signal input reaches the pipeline through an effect, so you must run pending effects before checking for requests. In Angular 20 and later, TestBed.tick() does this. Older versions use TestBed.flushEffects().
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { UsersStore } from './users.store';
describe('UsersStore', () => {
it('loads users and clears the loading flag', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting(), UsersStore],
});
const store = TestBed.inject(UsersStore);
const http = TestBed.inject(HttpTestingController);
TestBed.tick();
const req = http.expectOne((r) => r.url === '/api/users');
expect(store.loading()).toBe(true);
req.flush([{ id: 1, name: 'Alice' }]);
expect(store.users()).toEqual([{ id: 1, name: 'Alice' }]);
expect(store.loading()).toBe(false);
http.verify();
});
it('keeps working after a failed request', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting(), UsersStore],
});
const store = TestBed.inject(UsersStore);
const http = TestBed.inject(HttpTestingController);
TestBed.tick();
http.expectOne((r) => r.url === '/api/users').error(new ProgressEvent('error'));
expect(store.error()).not.toBeNull();
store.setQuery('bob');
TestBed.tick();
http.expectOne((r) => r.url === '/api/users').flush([]);
expect(store.error()).toBeNull();
});
});The second test checks the behavior tapResponse provides: after an error, a new query still triggers a request.
Common mistakes
- Subscribing manually inside the pipeline. Calling
.subscribe()insidetapbypasses cancellation and cleanup. Return the observable fromswitchMapinstead. - Putting
tapResponseon the outer pipe. A single error then ends the method. - Reading a signal inside the pipeline. Reading
store.query()insideswitchMapreturns the current value but does not make the method react to changes. Pass the signal as the argument instead. - Expecting synchronous results from signal input. The first emission waits for an effect, so tests and code that run right after creation must allow for it.
- Wrong operator for the job.
switchMapon a save request can cancel a write that already reached the server. UseconcatMaporexhaustMapfor writes.
Exercise
A teammate writes a method with rxMethod<number>(pipe(switchMap((id) => http.get<User>(/api/users/${id})), tapResponse({ next: (user) => patchState(store, { selected: user }), error: () => patchState(store, { error: 'failed' }) }))). After one 404 response, selecting another user never loads. What is wrong, and how do you fix it?
Show answer
tapResponse is on the outer pipeline, after switchMap. The 404 error reaches the outer stream, so the rxMethod subscription ends, and later ids are ignored. Move tapResponse into the inner pipe, directly after http.get(...), so the error is handled there and the outer stream keeps running.
Exercise
Why does store.loadByQuery(store.query) in onInit keep reloading when the query changes, while store.loadByQuery(store.query()) loads only once?
Show answer
The first call passes the signal, and rxMethod watches a signal argument through an effect, so every change is sent into the pipeline. The second call reads the current value and passes a plain string, so the pipeline runs once with that string.