Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 74 ยท Dependency Injection and Services

State Management with Signals and Services

Manage shared state in Angular with signal-based services - immutable updates, derived state, scoping, a look at NgRx SignalStore and when a bigger tool pays off.

Sooner or later two components need the same data. A header shows the number of items in the cart, a product page adds to it, and a checkout page empties it. Passing values down through inputs and back up through outputs works for a parent and its child, but not for components in different parts of the page. You need one place that owns the state, and every component reads from it.

In Angular that place is usually a service holding signals. You already have everything required: a root-provided service is a singleton (Services and Dependency Injection), signals notify readers when they change (Signals in Components), and computed() derives values. This lesson turns those pieces into a repeatable pattern, shows the same idea in the popular NgRx SignalStore library, and gives you honest criteria for when a heavier tool is worth it.

Real versus stand-in. The typescript blocks are real Angular (and real NgRx) and read-only, because the site cannot run the Angular compiler or install packages. The runnable examples use a hand-written mini signal implementation with a store written on top of it, so you can see how updates, derived state and logs behave. Real signals differ in detail (for example, effects are scheduled and a computed() skips notifying readers when its result did not change).

The signal store pattern

A signal store service follows five habits:

  1. The whole state lives in one private signal holding a plain object.
  2. Public values are computed() slices and derived values, read-only by construction.
  3. Changes happen through methods that describe intent (add, toggle), never through callers writing to the signal.
  4. Every update is immutable: build new objects and arrays rather than editing the old ones.
  5. The service is providedIn: 'root' for app-wide state, or listed in a component's providers for per-instance state (Providers, InjectionToken and Scopes).
TypeScript
import { computed, Injectable, signal } from '@angular/core';

export interface Todo { id: number; title: string; done: boolean }
export type Filter = 'all' | 'open' | 'done';

interface TodoState { todos: Todo[]; filter: Filter }

@Injectable({ providedIn: 'root' })
export class TodoStore {
  private readonly state = signal<TodoState>({ todos: [], filter: 'all' });
  private nextId = 1;

  readonly todos = computed(() => this.state().todos);
  readonly filter = computed(() => this.state().filter);
  readonly remaining = computed(() => this.todos().filter(t => !t.done).length);
  readonly visible = computed(() => {
    const { todos, filter } = this.state();
    if (filter === 'all') return todos;
    return todos.filter(t => (filter === 'done' ? t.done : !t.done));
  });

  add(title: string): void {
    this.patch(s => ({ todos: [...s.todos, { id: this.nextId++, title, done: false }] }));
  }

  toggle(id: number): void {
    this.patch(s => ({ todos: s.todos.map(t => (t.id === id ? { ...t, done: !t.done } : t)) }));
  }

  remove(id: number): void {
    this.patch(s => ({ todos: s.todos.filter(t => t.id !== id) }));
  }

  setFilter(filter: Filter): void {
    this.patch(() => ({ filter }));
  }

  private patch(change: (s: TodoState) => Partial<TodoState>): void {
    this.state.update(s => ({ ...s, ...change(s) }));
  }
}

Any component can now inject(TodoStore) and read store.visible() in its template. The header can show store.remaining() while the list shows store.visible(); both update when toggle() runs, and neither component knows the other exists.

flowchart LR
  A["TodoList component"] -- "store.toggle(id)" --> S
  B["AddTodo component"] -- "store.add(title)" --> S
  subgraph S["TodoStore (service)"]
    ST["state signal"] --> D["computed: visible, remaining"]
  end
  D -- "read in templates" --> A
  D -- "read in templates" --> H["Header badge component"]

Components send intent into the store through methods; derived signals flow back out to every reader.

Why immutable updates matter

Signals detect changes with Object.is. If a method pushes into state().todos and keeps the same array, the signal is not notified and OnPush components stay stale (see Change Detection, OnPush and Zoneless). Building a new array with spread or map() gives a new identity and makes the change visible. The spread { ...t, done: !t.done } copies only the one todo that changed, so untouched todos keep their identity. That is called structural sharing and it keeps updates cheap and lets track in @for reuse the existing DOM.

The stand-in below runs that store against a tiny signal implementation. An effect plays the part of a template reading visible and remaining, and the last lines check array identity.

TypeScript A signal store service with immutable updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each action logs once, because the effect re-runs after the state changes. After setFilter('open') the list narrows without touching the todos, and the identity checks at the end show structural sharing at work: a filter change leaves the todos array untouched, while a toggle replaces it.

Loading data into a store

Real stores usually fetch from a server. Keep the loading and error flags in the same state object so the UI can render all three states from one place, and have the store method call HttpClient, or use resource() for read-only data (linkedSignal, resource and httpResource). Components still only call methods and read signals.

TypeScript
interface ProductState {
  items: Product[];
  loading: boolean;
  error: string | null;
}

load(): void {
  this.patch({ loading: true, error: null });
  this.http.get<Product[]>('/api/products').subscribe({
    next: items => this.patch({ items, loading: false }),
    error: () => this.patch({ loading: false, error: 'Could not load products' }),
  });
}

NgRx SignalStore: the same pattern as a library

Writing patch() and the computed slices by hand gets repetitive across many stores. NgRx SignalStore (the @ngrx/signals package) is the same pattern packaged as composable features: withState for state, withComputed for derived values, withMethods for actions, and patchState for immutable updates. Every state property automatically becomes a signal.

TypeScript
import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';

interface TodoState { todos: Todo[]; filter: Filter }

export const TodoStore = signalStore(
  { providedIn: 'root' },
  withState<TodoState>({ todos: [], filter: 'all' }),
  withComputed(({ todos }) => ({
    remaining: computed(() => todos().filter(t => !t.done).length),
  })),
  withMethods(store => ({
    add(title: string): void {
      patchState(store, state => ({
        todos: [...state.todos, { id: Date.now(), title, done: false }],
      }));
    },
    setFilter(filter: Filter): void {
      patchState(store, { filter });
    },
  })),
);

// In a component: readonly store = inject(TodoStore);  then  store.remaining(), store.add('...')

It is a third-party package, so check its documentation for the current API and extra features such as entity helpers, custom features and dev tools. Nothing about it is magic: if you understand the hand-written service above, you understand SignalStore.

When to reach for classic NgRx Store

The original NgRx Store is a Redux-style design: components dispatch actions, reducers compute the next state as a pure function, selectors read memoized slices, and effects handle side effects. Its value is not shorter code but traceability: every change is a named, logged action, so you can replay history, undo, debug with a time-travel tool, and enforce one strict flow across a large team.

The stand-in below is the core of that idea: a pure reducer, an action log, and "time travel" by replaying the log.

TypeScript Actions, a pure reducer and time travel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Because the reducer is pure and every change is recorded as data, the state at any moment can be rebuilt from the log. That is the capability NgRx Store adds, at the cost of more files and ceremony: an action, a reducer branch and often a selector for each change.

flowchart TD
  Q1{"Does only one component<br/>or a parent and child use it?"} -- yes --> L["Local signals and inputs"]
  Q1 -- no --> Q2{"Do you need an audit trail,<br/>undo or strict team conventions?"}
  Q2 -- no --> SV["Signal store in a service,<br/>or NgRx SignalStore for less boilerplate"]
  Q2 -- yes --> NG["NgRx Store with actions,<br/>reducers and effects"]

A rough guide: start at the top and move down only when the simpler tool hurts.

A sensible default is local signals first, a service store when state is shared, SignalStore when you want conventions without ceremony, and classic NgRx Store when traceability across a large app is a real requirement. Moving up later is straightforward because the components already talk to the store through methods and signals.

Classic NgRx Store in real code

If you do choose classic NgRx Store, these are the pieces and how they connect. Install with ng add @ngrx/store, ng add @ngrx/effects and ng add @ngrx/store-devtools; the real code below is read-only because the site cannot compile Angular, and the runnable stand-in follows it.

Actions are named events. createActionGroup builds a typed set for one source:

TypeScript
// todos.actions.ts
import { createActionGroup, emptyProps, props } from '@ngrx/store';
import { Todo } from './todo.model';

export const TodoActions = createActionGroup({
  source: 'Todos',
  events: {
    'Load': emptyProps(),
    'Load Success': props<{ todos: Todo[] }>(),
    'Load Failure': props<{ error: string }>(),
    'Add': props<{ title: string }>(),
    'Toggle': props<{ id: number }>(),
  },
});

The reducer is a pure function from state and action to the next state. createFeature also generates selectors for each state property:

TypeScript
// todos.feature.ts
import { createFeature, createReducer, createSelector, on } from '@ngrx/store';

interface TodosState {
  items: Todo[];
  loading: boolean;
  error: string | null;
}
const initialState: TodosState = { items: [], loading: false, error: null };

export const todosFeature = createFeature({
  name: 'todos',
  reducer: createReducer(
    initialState,
    on(TodoActions.load, (state) => ({ ...state, loading: true, error: null })),
    on(TodoActions.loadSuccess, (state, { todos }) => ({ ...state, items: todos, loading: false })),
    on(TodoActions.loadFailure, (state, { error }) => ({ ...state, loading: false, error })),
    on(TodoActions.add, (state, { title }) => ({
      ...state,
      items: [...state.items, { id: Date.now(), title, done: false }],
    })),
    on(TodoActions.toggle, (state, { id }) => ({
      ...state,
      items: state.items.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    })),
  ),
  extraSelectors: ({ selectItems }) => ({
    selectRemaining: createSelector(selectItems, (items) => items.filter((t) => !t.done).length),
  }),
});

Selectors read slices of state and are memoized: a selector recomputes only when its inputs change, and returns the same result object otherwise, which keeps components from re-rendering needlessly. todosFeature.selectItems, selectLoading, selectError and the custom selectRemaining exist now.

Effects handle side effects, such as HTTP calls, in response to actions. An effect listens to the Actions stream and emits new actions:

TypeScript
// todos.effects.ts
import { inject } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, map, of, switchMap } from 'rxjs';

export const loadTodos = createEffect(
  (actions$ = inject(Actions), api = inject(TodoApi)) =>
    actions$.pipe(
      ofType(TodoActions.load),
      switchMap(() =>
        api.list().pipe(
          map((todos) => TodoActions.loadSuccess({ todos })),
          catchError((e) => of(TodoActions.loadFailure({ error: String(e.message ?? e) }))),
        ),
      ),
    ),
  { functional: true },
);

Wiring and use:

TypeScript
// app.config.ts
import { provideStore } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { provideStoreDevtools } from '@ngrx/store-devtools';

export const appConfig: ApplicationConfig = {
  providers: [
    provideStore({ [todosFeature.name]: todosFeature.reducer }),
    provideEffects({ loadTodos }),
    provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),
  ],
};

// a component
export class TodoPage {
  private readonly store = inject(Store);
  protected readonly items = this.store.selectSignal(todosFeature.selectItems);
  protected readonly remaining = this.store.selectSignal(todosFeature.selectRemaining);

  constructor() { this.store.dispatch(TodoActions.load()); }
  add(title: string): void { this.store.dispatch(TodoActions.add({ title })); }
}

selectSignal turns a selector into a signal, so the template stays modern: @for (todo of items(); track todo.id). The browser Redux DevTools extension, fed by provideStoreDevtools, shows the action log and lets you step backwards and forwards, which is the time travel from the stand-in above, for your real app. Check the NgRx documentation for the exact API of the version you install, because the helper functions have been refined over several releases.

The next stand-in models the other two ideas: a memoized selector that recomputes only when its input changes, and an effect that turns a load action into a success or failure action through an async call.

TypeScript Selectors with memoization and an effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first load fails, the effect dispatches loadFailure, and the reducer records the error. The second load succeeds. Asking for remaining twice computes once, because the items did not change; after a toggle the items are a new array, so the selector recomputes. Components, the reducer and the effect never call each other directly: everything is an action in the log.

The honest cost. For this one feature the NgRx version needs an actions file, a feature file, an effects file and wiring, where a signal store service needs one class. That trade (more files for a strict, inspectable flow) is the whole decision. Many teams use NgRx for the few pieces of truly global, shared state and plain signals everywhere else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a store service expose computed() or asReadonly() signals instead of its writable state signal?

    Read-only exposure keeps every change inside methods that describe intent, which makes the data flow easy to follow and debug.
  2. 2. A store method does this.state().todos.push(newTodo). What goes wrong?

    Signals compare with Object.is, so mutating in place is invisible. Use update() with a new array, such as [...todos, newTodo].
  3. 3. What is structural sharing in the update { ...todo, done: true } inside map()?

    Untouched items stay identical, which keeps updates cheap and lets track in @for reuse DOM nodes.
  4. 4. What does NgRx SignalStore mainly provide?

    It packages the hand-written store pattern so that state properties become signals and updates go through patchState.
  5. 5. When is classic NgRx Store (actions and reducers) worth its ceremony?

    Its main benefit is traceability: every change is a named action that a pure reducer applies, so the history can be replayed.

Summary

  • Shared state lives in a service: one private state signal, computed() slices, methods that express intent and immutable updates.
  • Mutating in place is invisible to signals; build new objects and arrays so changes are detected and unchanged items keep their identity.
  • Provide at root for app-wide state or in a component's providers for per-instance state.
  • NgRx SignalStore packages the same pattern with withState, withComputed, withMethods and patchState.
  • Reach for classic NgRx Store when you need an action history, undo or strict structure across a large team.

Next: Routing Basics.