← Back to Angular, page 4

angular-0072 · Medium mid

What is NgRx SignalStore, and how do withState, withComputed, withMethods, rxMethod and patchState fit together?

SignalStore builds a store service from composable features. withState defines state as signals, withComputed adds derived values, withMethods adds the operations that change state through patchState, and rxMethod connects RxJS pipelines such as an HTTP load to the store. It gives structure with much less boilerplate than the classic Store.

Full answer

signalStore returns an injectable class made from features, in order. Each feature can use what earlier features added.

ts
export const CourseStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),
  withComputed(({ courses, query }) => ({ visible: computed(() => ...) })),
  withMethods((store, api = inject(CourseApi)) => ({ ... })),
  withHooks({ onInit(store) { store.load(); } }),
);
  • withState turns every top-level property into a signal (store.courses()) and keeps the state object as a deep signal. Properties are read-only for outsiders.
  • withComputed adds derived signals.
  • withMethods adds methods. State is changed only through patchState(store, { ... }) or with an updater function, which keeps changes in one place. The state stays protected from outside writes by default.
  • rxMethod<T>(pipe(...)) creates a method that accepts a value, a signal, or an Observable and runs an RxJS pipeline. It is how you debounce, switchMap to an API call, and tap the result into state. It cleans up with the store.
  • withHooks runs code when the store is created or destroyed.
  • providedIn: 'root' makes it global. Without it, put the store in providers of a route or component to scope the state to that tree.
  • Extra packages add features: withEntities for collections and signalStoreFeature for reusable custom features, such as a shared loading state.

When to use it: component or feature state that needs structure, but not the ceremony of actions, reducers, and effects. When to prefer the classic Store: large teams that want strict action logs, DevTools time travel, and cross-feature event handling.

Testing is simple: create the store with TestBed, call methods, and check signals. Fake the API in providers.

typescript
import { computed, inject, Injectable } from '@angular/core';
import { patchState, signalStore, withComputed, withHooks, withMethods, withState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { tapResponse } from '@ngrx/operators';
import { Observable, of, pipe, switchMap, tap } from 'rxjs';

export interface Course {
  id: number;
  title: string;
}

interface CourseState {
  courses: Course[];
  query: string;
  loading: boolean;
  error: string | null;
}

const initialState: CourseState = { courses: [], query: '', loading: false, error: null };

@Injectable({ providedIn: 'root' })
export class CourseApi {
  list(): Observable<Course[]> {
    return of([
      { id: 1, title: 'Angular basics' },
      { id: 2, title: 'RxJS in practice' },
    ]);
  }
}

export const CourseStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),
  withComputed(({ courses, query }) => ({
    visible: computed(() => courses().filter((c) => c.title.toLowerCase().includes(query().toLowerCase()))),
    count: computed(() => courses().length),
  })),
  withMethods((store, api = inject(CourseApi)) => ({
    setQuery(query: string): void {
      patchState(store, { query });
    },
    load: rxMethod<void>(
      pipe(
        tap(() => patchState(store, { loading: true, error: null })),
        switchMap(() =>
          api.list().pipe(
            tapResponse({
              next: (courses) => patchState(store, { courses, loading: false }),
              error: () => patchState(store, { loading: false, error: 'Could not load courses' }),
            }),
          ),
        ),
      ),
    ),
  })),
  withHooks({
    onInit(store) {
      store.load();
    },
  }),
);

Angular 20.3 with NgRx Signals 20.1 and NgRx Operators 20.1, type-checked. A Karma spec in headless Chrome checks that `onInit` loads the courses, that `setQuery` filters `visible`, and that a failing API sets the error message. `tapResponse` handles success and error inside the inner Observable.

Key points

  • Features compose in order: state, computed, methods, hooks.
  • Change state only through `patchState`. Outsiders see read-only signals.
  • `rxMethod` connects RxJS pipelines (debounce, `switchMap`, HTTP) to the store.
  • Scope the store with `providers`, or make it global with `providedIn: 'root'`.

Common mistakes

  • Writing to state from components instead of calling store methods.
  • Forgetting error handling inside `rxMethod`, so one failed request ends the pipeline.
  • Putting unrelated features into one global store.

Follow-ups

  • How does `rxMethod` differ from calling `subscribe` yourself?
  • How would you share a loading and error feature between stores?
  • How do you test a SignalStore?

Tips

  • Contrast it with the classic Store by naming what you gain (less code) and lose (action log).
  • Show `patchState` as the single door for state changes.
  • Mention scoping with `providers`.

Evaluation rubric

  • Explains each feature function in order.
  • Uses rxMethod with error handling.
  • Knows when to choose it over the classic Store.