Blog

Part 15 · State with Signals and Services: A Small Store Without a Library

When several components need the same data, keep it in a store service. This part builds one with a private signal, read-only views, computed selectors and actions, then scopes it per component, saves it and loads data.

So far each piece of state has lived in one component. A parent held a list, passed it down with inputs and heard about changes through outputs. That works until two components far apart in the tree need the same data. Then every component between them has to carry it.

This part moves shared state into a store: a service that owns a signal, hands out read-only views of it, and offers methods that change it. We build one for a todo list used by three components, give each copy of a form its own store, save a store to localStorage and load data into one. It builds on signals from Part 3, effect from Part 8 and services from Part 13. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It has a service with a signal in it and two small components. Neither component has an input or an output, and neither knows the other exists.

// src/app/app.ts
import { Component, Service, inject, signal } from '@angular/core';

@Service()
export class CounterStore {
  readonly count = signal(0);
}

@Component({
  selector: 'app-add-button',
  template: `<button (click)="add()">Add one</button>`,
})
export class AddButton {
  private readonly store = inject(CounterStore);

  protected add() {
    this.store.count.update((n) => n + 1);
  }
}

@Component({
  selector: 'app-badge',
  template: `<p>Badge: {{ store.count() }}</p>`,
})
export class Badge {
  protected readonly store = inject(CounterStore);
}

@Component({
  selector: 'app-root',
  imports: [AddButton, Badge],
  template: `
    <app-badge />
    <app-add-button />
  `,
})
export class App {}

Real code would put each class in its own file. One file keeps this first try short.

Before you read on, guess. Click Add one twice. What does the badge say?

Here’s what happens. After two clicks, the page shows:

Badge: 2
Add one

The badge says 2. Part 13 explained why: @Service() makes one CounterStore for the whole app, and inject(CounterStore) in a field hands every component that same object. AddButton changes the signal inside it. Badge reads that signal, so Angular redraws it. No input or output was needed.

Now look at what AddButton is allowed to do. It could just as well call this.store.count.set(-50). So could every other component that injects the store. When the badge shows a wrong number, you’d have to search the whole app for the line that wrote it. The rest of this part is about closing that door.

When component state isn’t enough

Picture a shop page. The header shows how many items are in the cart. A product card, four components further down, has the Add to cart button. With only inputs and outputs, App holds the cart. The count goes down through the header. The click goes up from the card through the product grid, the product list and the page, each one with an output that does nothing but pass the event on. People call that prop drilling: a value drilled through layers that don’t use it.

It isn’t wrong. For a parent and its child, inputs and outputs are the right tool (Part 5, Part 6). They make the data flow easy to see. But when the components are far apart, or there are many of them, the middle layers fill up with plumbing. Each new feature touches all of them.

A service fixes the distance. Any component can inject it, wherever it sits in the tree. What we need on top of that is a rule about who may change the data.

The store pattern

Here’s the same counter as a store: a service that owns its state and decides how it changes.

// src/app/app.ts
import { Component, Service, computed, inject, signal } from '@angular/core';

@Service()
export class CounterStore {
  private readonly countState = signal(0);

  readonly count = this.countState.asReadonly();
  readonly isBig = computed(() => this.count() >= 3);

  increment() {
    this.countState.update((n) => n + 1);
  }

  reset() {
    this.countState.set(0);
  }
}

@Component({
  selector: 'app-add-button',
  template: `
    <button (click)="store.increment()">Add one</button>
    <button (click)="store.reset()">Reset</button>
  `,
})
export class AddButton {
  protected readonly store = inject(CounterStore);
}

@Component({
  selector: 'app-badge',
  template: `<p>Badge: {{ store.count() }}{{ store.isBig() ? ' (big)' : '' }}</p>`,
})
export class Badge {
  protected readonly store = inject(CounterStore);
}

@Component({
  selector: 'app-root',
  imports: [AddButton, Badge],
  template: `
    <app-badge />
    <app-add-button />
  `,
})
export class App {}

Click Add one three times. The page shows:

Badge: 3 (big)
Add oneReset

The two buttons run together as Add oneReset because buttons sit on one line, and the page text joins them.

The store has three kinds of members:

  • Private state. countState is the only writable signal. private is TypeScript for “only code inside this class can use it”. Components can’t see it, so they can’t write it.
  • Public reads. count is countState.asReadonly(), the read-only view we met in Part 3. It follows the same value, but it has no set or update. isBig is a computed worked out from the state. A computed that picks out or works out part of a store’s state is often called a selector.
  • Actions. increment and reset are ordinary methods. They’re the only way the state changes, so they’re the only place to look when it changes wrongly.

The components barely changed. They inject the store and read its signals in the template, exactly as they’d read their own. They call actions instead of writing.

If a component tries to write count anyway, the build stops with TS2339. We’ll read that error in a worked example below.

A store with real state

A counter has one number. Most stores hold several related values: a list, the current filter, a loading flag. Keep them together in one signal holding an object, and describe its shape with an interface:

// src/app/todo-store.ts
import { Service, computed, signal } from '@angular/core';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';

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

@Service()
export class TodoStore {
  private readonly state = signal<TodoState>({
    todos: [
      { id: 1, text: 'Buy milk', done: false },
      { id: 2, text: 'Call Ana', done: true },
    ],
    filter: 'all',
  });
  private nextId = 3;

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

  add(text: string) {
    const todo = { id: this.nextId++, text, done: false };
    this.state.update((s) => ({ ...s, todos: [...s.todos, todo] }));
  }

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

  remove(id: number) {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
  }

  setFilter(filter: Filter) {
    this.state.update((s) => ({ ...s, filter }));
  }
}

New TypeScript here:

  • type Filter = 'all' | 'active' | 'done' is a union type: a Filter is one of those three strings and nothing else. setFilter('finished') won’t build.
  • interface TodoState isn’t exported. Only the store needs the whole shape. Components see the pieces the selectors hand out.
  • const { todos, filter } = this.state(); is destructuring: it reads the state once and pulls out two properties into two constants.

Every action builds a new state object with { ...s, ... }, and a new array whenever the list changes. That’s the rule from Part 3: a signal sees a change only when it gets a new value. toggle goes one level deeper. It makes a new array with map, and a new object for the one todo that changed. The other todos are the same objects as before.

The selectors are where derived state lives. visible is the filtered list. remaining counts what’s left. Neither is stored, so neither can drift out of step with todos. A sorted list, a total price or a “has errors” flag belong here too.

remaining reads this.todos(), not this.state(). That matters. When only the filter changes, todos recomputes and returns the same array as before. A computed compares its new value with its old one, the same array means “no change”, so remaining doesn’t run again and nothing that reads it is redrawn.

TodoInput TodoList TodoFooter TodoStore public, read-only visible() remaining() actions add() toggle() remove() setFilter() state = signal<TodoState>(…) private: only the store's own actions write it reads a signal calls an action updates the state

Components read the public signals and call actions. No component has an arrow into the private state.

The blue arrows are reads: a template calling visible() or remaining(), and a computed reading the state. The red arrows are calls into actions. Only the actions write the state.

Worked example: three components, one store

Now three components share that store. TodoInput adds todos. TodoList shows them and lets you tick or remove one. TodoFooter shows the count and the filter buttons. None of them talks to another, and App passes nothing down.

Here are all five files. The store is the one above, repeated so you can paste each file in one go.

// src/app/todo-store.ts
import { Service, computed, signal } from '@angular/core';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';

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

@Service()
export class TodoStore {
  private readonly state = signal<TodoState>({
    todos: [
      { id: 1, text: 'Buy milk', done: false },
      { id: 2, text: 'Call Ana', done: true },
    ],
    filter: 'all',
  });
  private nextId = 3;

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

  add(text: string) {
    const todo = { id: this.nextId++, text, done: false };
    this.state.update((s) => ({ ...s, todos: [...s.todos, todo] }));
  }

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

  remove(id: number) {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
  }

  setFilter(filter: Filter) {
    this.state.update((s) => ({ ...s, filter }));
  }
}
// src/app/todo-input.ts
import { Component, inject, signal } from '@angular/core';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-input',
  template: `
    <label>New todo <input [value]="text()" (input)="text.set($event.target.value)" /></label>
    <button (click)="add()">Add</button>
  `,
})
export class TodoInput {
  private readonly store = inject(TodoStore);
  protected readonly text = signal('');

  protected add() {
    const text = this.text().trim();
    if (!text) return;
    this.store.add(text);
    this.text.set('');
  }
}
// src/app/todo-list.ts
import { Component, inject } from '@angular/core';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-list',
  template: `
    <ul>
      @for (todo of store.visible(); track todo.id) {
        <li>
          <label>
            <input type="checkbox" [checked]="todo.done" (change)="store.toggle(todo.id)" />
            {{ todo.text }}
          </label>
          <button (click)="store.remove(todo.id)">Remove</button>
        </li>
      } @empty {
        <li>Nothing here.</li>
      }
    </ul>
  `,
})
export class TodoList {
  protected readonly store = inject(TodoStore);
}
// src/app/todo-footer.ts
import { Component, inject } from '@angular/core';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-footer',
  template: `
    <p>{{ store.remaining() }} left</p>
    <button (click)="store.setFilter('all')">All</button>
    <button (click)="store.setFilter('active')">Active</button>
    <button (click)="store.setFilter('done')">Done</button>
  `,
})
export class TodoFooter {
  protected readonly store = inject(TodoStore);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { TodoFooter } from './todo-footer';
import { TodoInput } from './todo-input';
import { TodoList } from './todo-list';

@Component({
  selector: 'app-root',
  imports: [TodoInput, TodoList, TodoFooter],
  template: `
    <app-todo-input />
    <app-todo-list />
    <app-todo-footer />
  `,
})
export class App {}

Some things to notice:

  • TodoInput keeps the text being typed in its own signal. Nobody else needs half-typed text, so it isn’t store state. Only a finished todo goes to the store. Local state stays local.
  • TodoInput injects the store as private, because only its class uses it. TodoList and TodoFooter use it in their templates, so they make it protected.
  • The list and the footer call actions straight from the template, like store.toggle(todo.id). That’s fine for a single call.

When the page loads, it shows:

New todo Add
Buy milk Remove
Call Ana Remove
1 left
AllActiveDone

Type Water plants into New todo and click Add. The page shows:

New todo Add
Buy milk Remove
Call Ana Remove
Water plants Remove
2 left
AllActiveDone

The list got a new line and the footer went from 1 left to 2 left. TodoInput doesn’t know either of them exists. Now tick Buy milk and click Active:

New todo Add
Water plants Remove
1 left
AllActiveDone

Only Water plants is still to do, so it’s the only one the Active filter shows. The tick happened in the list, and the count changed in the footer.

Worked example: a component tries to write

A teammate wants a Clear all button in the footer. The footer has store.todos, and a signal has set, so they write this:

// src/app/todo-footer.ts
import { Component, inject } from '@angular/core';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-footer',
  template: `
    <p>{{ store.remaining() }} left</p>
    <button (click)="store.setFilter('all')">All</button>
    <button (click)="store.setFilter('active')">Active</button>
    <button (click)="store.setFilter('done')">Done</button>
    <button (click)="clearAll()">Clear all</button>
  `,
})
export class TodoFooter {
  protected readonly store = inject(TodoStore);

  protected clearAll() {
    this.store.todos.set([]);
  }
}

ng serve refuses to build it:

✘ [ERROR] TS2339: Property 'set' does not exist on type 'Signal<Todo[]>'. [plugin angular-compiler]

    src/app/todo-footer.ts:19:21:
      19 │     this.store.todos.set([]);
         ╵                      ~~~

Read it piece by piece:

  • TS2339 means “this property doesn’t exist on this type”, as in Part 3.
  • Property 'set' does not exist on type 'Signal<Todo[]>' says why. todos is a computed, and a computed is a Signal: read-only. The same goes for anything from asReadonly(). Only a WritableSignal has set and update, and the store’s only writable signal is private.
  • src/app/todo-footer.ts:19:21 points at set, in the footer. (The real output starts the path with your project’s folder.)

The store is doing its job. The error isn’t a reason to make state public. It’s a sign that the store is missing an action. Clearing everything is a big hammer, so let’s add the action people usually want, Clear done, to the store:

// src/app/todo-store.ts
import { Service, computed, signal } from '@angular/core';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';

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

@Service()
export class TodoStore {
  private readonly state = signal<TodoState>({
    todos: [
      { id: 1, text: 'Buy milk', done: false },
      { id: 2, text: 'Call Ana', done: true },
    ],
    filter: 'all',
  });
  private nextId = 3;

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

  add(text: string) {
    const todo = { id: this.nextId++, text, done: false };
    this.state.update((s) => ({ ...s, todos: [...s.todos, todo] }));
  }

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

  remove(id: number) {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
  }

  clearDone() {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => !t.done) }));
  }

  setFilter(filter: Filter) {
    this.state.update((s) => ({ ...s, filter }));
  }
}
// src/app/todo-footer.ts
import { Component, inject } from '@angular/core';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-footer',
  template: `
    <p>{{ store.remaining() }} left</p>
    <button (click)="store.setFilter('all')">All</button>
    <button (click)="store.setFilter('active')">Active</button>
    <button (click)="store.setFilter('done')">Done</button>
    <button (click)="store.clearDone()">Clear done</button>
  `,
})
export class TodoFooter {
  protected readonly store = inject(TodoStore);
}

Click Clear done. Call Ana was done, so it goes:

New todo Add
Buy milk Remove
1 left
AllActiveDoneClear done

Every way the todos can change is now a method on TodoStore, with a name that says what it does. If a todo ever vanishes when it shouldn’t, there are two methods that remove todos, and both are in one file.

Worked example: a new outer object isn’t enough

Actions must not change the arrays and objects already in the state. Here’s a version of add that looks safe, because it does return a new state object:

// src/app/todo-store.ts
import { Service, computed, signal } from '@angular/core';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';

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

@Service()
export class TodoStore {
  private readonly state = signal<TodoState>({
    todos: [
      { id: 1, text: 'Buy milk', done: false },
      { id: 2, text: 'Call Ana', done: true },
    ],
    filter: 'all',
  });
  private nextId = 3;

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

  add(text: string) {
    const todo = { id: this.nextId++, text, done: false };
    this.state.update((s) => {
      s.todos.push(todo);
      return { ...s };
    });
  }

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

  remove(id: number) {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
  }

  clearDone() {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => !t.done) }));
  }

  setFilter(filter: Filter) {
    this.state.update((s) => ({ ...s, filter }));
  }
}

Type Water plants into New todo and click Add. The page shows:

New todo Add
Buy milk Remove
Call Ana Remove
1 left
AllActiveDoneClear done

The todo isn’t there, and the count still says 1 left. Follow the signals:

  1. state got a new object, so it notified todos and visible.
  2. todos ran again and returned s.todos. That’s the same array it returned last time, with one more item pushed into it. A computed compares with Object.is, sees the same array, and says nothing changed. So remaining isn’t told anything.
  3. visible, with the filter on all, also returns that same array. The list isn’t told anything either.

The push did happen. Click Active, and the new todo shows up, because the filter makes a new array:

New todo Add
Buy milk Remove
Water plants Remove
1 left
AllActiveDoneClear done

The list is right now, and the count is still wrong. That makes this bug look random. The fix is the original add, which builds a new array: todos: [...s.todos, todo]. It’s the same rule as Part 3’s “don’t change a list in place”, and a new outer object doesn’t get around it.

For one level of nesting, spread syntax (...), map and filter are all you need. If you ever need a full independent copy of a deep object, structuredClone(value) makes one. You rarely need it in a store, and it copies everything, so selectors that compare arrays see every part as changed.

Saving the store

In Part 8 an effect saved settings to localStorage. A store is a good home for that effect, because the store is the one place that sees every change. Create it in the store’s constructor, which runs in an injection context:

// src/app/todo-store.ts
import { Service, computed, effect, signal } from '@angular/core';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';

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

const KEY = 'todos';

function loadTodos(): Todo[] {
  const saved = localStorage.getItem(KEY);
  return saved ? JSON.parse(saved) : [{ id: 1, text: 'Buy milk', done: false }];
}

@Service()
export class TodoStore {
  private readonly state = signal<TodoState>({ todos: loadTodos(), filter: 'all' });
  private nextId = Math.max(0, ...this.state().todos.map((t) => t.id)) + 1;

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

  constructor() {
    effect(() => {
      const todos = this.todos();
      localStorage.setItem(KEY, JSON.stringify(todos));
      console.log('saved', todos.length, 'todos');
    });
  }

  add(text: string) {
    const todo = { id: this.nextId++, text, done: false };
    this.state.update((s) => ({ ...s, todos: [...s.todos, todo] }));
  }

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

  remove(id: number) {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => t.id !== id) }));
  }

  clearDone() {
    this.state.update((s) => ({ ...s, todos: s.todos.filter((t) => !t.done) }));
  }

  setFilter(filter: Filter) {
    this.state.update((s) => ({ ...s, filter }));
  }
}

What changed:

  • The starting todos come from loadTodos(), as the settings did in Part 8. nextId starts one past the largest saved id, so new todos don’t reuse an id.
  • The effect reads this.todos(), the selector, not the whole state. The filter isn’t worth saving, and this way a filter change doesn’t trigger a save.

When the page loads, the effect runs once:

saved 1 todos

Click Active and All. Nothing is logged, because todos didn’t change. Then type Water plants, click Add and tick Buy milk. Two more saves:

saved 2 todos
saved 2 todos

Press F5 in your own project, and the todos are still there. The components didn’t change at all.

One store per feature, not one for everything

You could put the whole app’s state in one big AppStore. Don’t. A store per feature is easier to read and to test: TodoStore, CartStore, UserStore. Each one is small, each one has its own actions, and a component injects only what it uses.

A store can inject another store with inject() when it needs to read it. Keep the arrows going one way, though. If CartStore reads UserStore, UserStore shouldn’t also inject CartStore.

And not everything is store state. Text in a half-filled input, whether a menu is open, which tab is selected: if only one component cares, keep it in that component’s own signal.

Worked example: a store per component

@Service() gives the whole app one instance. Sometimes you want one per component instead. Think of a form wizard that can appear twice on a page. Each copy needs its own current step, and the step must be shared between the wizard and its child components.

Part 13 showed how: list the service in the component’s providers. That component gets its own instance, and every child inside it that injects the service gets that same instance.

// src/app/wizard-store.ts
import { Service, computed, signal } from '@angular/core';

@Service()
export class WizardStore {
  private readonly stepState = signal(1);

  readonly step = this.stepState.asReadonly();
  readonly isFirst = computed(() => this.step() === 1);
  readonly isLast = computed(() => this.step() === 3);

  next() {
    this.stepState.update((n) => Math.min(n + 1, 3));
  }

  back() {
    this.stepState.update((n) => Math.max(n - 1, 1));
  }
}
// src/app/wizard-nav.ts
import { Component, inject } from '@angular/core';
import { WizardStore } from './wizard-store';

@Component({
  selector: 'app-wizard-nav',
  template: `
    <button (click)="store.back()" [disabled]="store.isFirst()">Back</button>
    <button (click)="store.next()" [disabled]="store.isLast()">Next</button>
  `,
})
export class WizardNav {
  protected readonly store = inject(WizardStore);
}
// src/app/wizard.ts
import { Component, inject, input } from '@angular/core';
import { WizardNav } from './wizard-nav';
import { WizardStore } from './wizard-store';

@Component({
  selector: 'app-wizard',
  imports: [WizardNav],
  providers: [WizardStore],
  template: `
    <p>{{ title() }}: step {{ store.step() }} of 3</p>
    <app-wizard-nav />
  `,
})
export class Wizard {
  readonly title = input.required<string>();
  protected readonly store = inject(WizardStore);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Wizard } from './wizard';

@Component({
  selector: 'app-root',
  imports: [Wizard],
  template: `
    <app-wizard title="Sign up" />
    <app-wizard title="Feedback" />
  `,
})
export class App {}

Math.min and Math.max keep the step between 1 and 3. Click the first Next twice. The page shows:

Sign up: step 3 of 3
BackNext
Feedback: step 1 of 3
BackNext

The Sign up wizard is on step 3, and the Feedback wizard is still on step 1. Each <app-wizard> made its own WizardStore because of providers: [WizardStore]. When WizardNav asks for a WizardStore, Angular looks in the nearest component first and walks up. It finds the one its own wizard provided, and it never reaches the app-wide one.

Take providers out of Wizard, and both wizards share the single app-wide store: one Next moves both. Exercise 2 is about that bug.

If a store only makes sense per component, you can make the mistake impossible. @Service({ autoProvided: false }) tells Angular not to provide it app-wide. Then a component that forgets providers fails with error NG0201, No provider found for the store, instead of quietly sharing state.

Async actions: loading and errors

Real data comes from a server. Part 18 covers HttpClient and Part 19 covers resource, which handles much of this for you. The store side looks the same either way: an action starts the work, and the state records whether it’s loading, whether it failed, and what came back.

Here we fake the server with a Promise, JavaScript’s object for a result that arrives later. fetchUsers waits half a second with setTimeout, then either delivers three names or fails.

// src/app/user-store.ts
import { Service, computed, signal } from '@angular/core';

interface UserState {
  users: string[];
  loading: boolean;
  error: string | null;
}

function fetchUsers(fail: boolean): Promise<string[]> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (fail) reject(new Error('Server is down'));
      else resolve(['Ana', 'Ben', 'Chen']);
    }, 500);
  });
}

@Service()
export class UserStore {
  private readonly state = signal<UserState>({ users: [], loading: false, error: null });

  readonly users = computed(() => this.state().users);
  readonly loading = computed(() => this.state().loading);
  readonly error = computed(() => this.state().error);

  async load(fail = false) {
    this.state.update((s) => ({ ...s, loading: true, error: null }));
    try {
      const users = await fetchUsers(fail);
      this.state.update((s) => ({ ...s, users, loading: false }));
    } catch (e) {
      const error = e instanceof Error ? e.message : 'Unknown error';
      this.state.update((s) => ({ ...s, loading: false, error }));
    }
  }
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { UserStore } from './user-store';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="store.load()">Load users</button>
    <button (click)="store.load(true)">Load with an error</button>
    @if (store.loading()) {
      <p>Loading...</p>
    } @else if (store.error()) {
      <p>Error: {{ store.error() }}</p>
    } @else {
      <p>Users: {{ store.users().join(', ') || 'none yet' }}</p>
    }
  `,
})
export class App {
  protected readonly store = inject(UserStore);
}

New JavaScript here:

  • async load() makes load an async function. Inside it, await fetchUsers(fail) pauses load until the Promise has a result, without blocking the page. If the Promise fails, await throws, and catch gets the error.
  • string | null says error is a string or nothing.
  • fail = false gives the parameter a default, so load() means “don’t fail”.

Click Load users. At once, the page shows:

Load usersLoad with an error
Loading...

Wait a moment, and it shows:

Load usersLoad with an error
Users: Ana, Ben, Chen

Click Load with an error and wait:

Load usersLoad with an error
Error: Server is down

Look at where the second update comes from. The click ran load up to the await and stopped. The rest ran half a second later, from a timer, long after the click was handled. In Part 3 a plain field changed from a timer and the screen didn’t notice. Here it does, because the timer’s code ends in state.update. The signal tells Angular, and Angular redraws what read it. A new Angular 22 project has no zone.js watching timers, and it doesn’t need it.

Notice that the error keeps the users from the first load in the state. The template only hides them while the error shows. Whether to clear old data on an error is a choice; make it in the action, where you can see it.

When to reach for a library

The store in this part is plain Angular: a service, signals and methods. For many apps that’s all you need. If a team wants a fixed structure for many stores, with reusable features, the NgRx project publishes one built on signals, signalStore in the @ngrx/signals package. Community add-ons give it devtools. It’s a choice to make when the plain version starts repeating itself, not before.

In older code

Before signals, stores were built with RxJS, a library for streams of values that Part 20 introduces. You’ll see a BehaviorSubject, which holds a current value and tells subscribers when it changes, kept private, and a public asObservable() view of it, the same idea as asReadonly():

@Injectable({ providedIn: 'root' })
export class TodoStore {
  private readonly todosSubject = new BehaviorSubject<Todo[]>([]);
  readonly todos$ = this.todosSubject.asObservable();

  add(todo: Todo) {
    this.todosSubject.next([...this.todosSubject.value, todo]);
  }
}

Templates read it with the async pipe from Part 12: @for (todo of store.todos$ | async; track todo.id). The $ at the end of a name is a habit that marks an Observable. @Injectable({ providedIn: 'root' }) is the older way to write @Service(). The shape is the same as ours: private state, a read-only view, methods that write.

Best practices

  • Keep the writable signal private and expose read-only views. Use asReadonly() for a whole signal and computed for a piece of it. The compiler then stops other code from writing, which replaces “please don’t call set on this” comments.
  • Change state only in named actions. A method like clearDone() says what happened, and it’s the one place to look when that change goes wrong. It replaces set calls scattered across components.
  • Put derived values in selectors. A filtered list, a count or a total is a computed in the store, never a second stored value. It replaces keeping two values in step by hand.
  • Always build new arrays and objects in actions. Use spread, map and filter. Selectors compare with Object.is, so in-place changes are invisible to them.
  • One store per feature, scoped as narrowly as it needs. App-wide with @Service(), per component with providers. It replaces one global store that every component depends on.
  • Keep state that only one component uses in that component. A store is for data that’s shared.

Tips and traps

  • Making state public to fix TS2339. The build error disappears, and so does the guarantee. Add an action to the store instead.
  • Pushing into an array inside update. Returning { ...s } doesn’t help: a selector that returns the array sees the same array and reports no change. The list doesn’t update until something unrelated makes a new array. Build [...s.todos, todo].
  • Sorting a selector’s array in place. this.todos().sort(...) sorts the store’s own array, behind its back. Copy first: [...this.todos()].sort(...).
  • Forgetting providers on a per-instance store. Two wizards move together, because both got the app-wide store. Add providers: [WizardStore], or mark the store @Service({ autoProvided: false }) so forgetting fails loudly.
  • Expecting a component-scoped store to outlive its component. The store in providers is destroyed with the component. If the data must survive, it needs an app-wide store or localStorage.
  • Saving with an effect that reads the whole state. Every filter click writes to storage. Read only the selector you mean to save.

A store keeps its writable signal private, hands out read-only signals, and changes state only through its own methods.

Exercises

Exercise 1. Write a ScoreStore with a private score signal that starts at 0, a read-only score, a selector doubled, and two actions: add(points) and reset(). Use it from two components: ScoreButtons with +1, +5 and Reset buttons, and ScoreBoard showing Score: 6, doubled: 12 after you click +1 and +5. One file is fine.

Exercise 2. This page has two tally panels. Click the first + and both panels change. Why? Fix it so each panel keeps its own count.

// src/app/app.ts
import { Component, Service, inject, input, signal } from '@angular/core';

@Service()
export class TallyStore {
  private readonly countState = signal(0);
  readonly count = this.countState.asReadonly();

  add() {
    this.countState.update((n) => n + 1);
  }
}

@Component({
  selector: 'app-tally',
  template: `
    <p>{{ name() }}: {{ store.count() }}</p>
    <button (click)="store.add()">+</button>
  `,
})
export class Tally {
  readonly name = input.required<string>();
  protected readonly store = inject(TallyStore);
}

@Component({
  selector: 'app-root',
  imports: [Tally],
  template: `
    <app-tally name="Cats" />
    <app-tally name="Dogs" />
  `,
})
export class App {}
Cats: 1
+
Dogs: 1
+

Exercise 3. Here’s a small store of names. Add a selector sorted that lists the names in alphabetical order, and show it under the names in the order they were added. After you click Add Ana, the page should show Added: Cy, Ben, Ana and Sorted: Ana, Ben, Cy. Hint: sort() changes the array it’s called on.

// src/app/app.ts
import { Component, Service, inject, signal } from '@angular/core';

@Service()
export class NameStore {
  private readonly namesState = signal(['Cy', 'Ben']);
  readonly names = this.namesState.asReadonly();

  add(name: string) {
    this.namesState.update((list) => [...list, name]);
  }
}

@Component({
  selector: 'app-root',
  template: `
    <p>Added: {{ store.names().join(', ') }}</p>
    <button (click)="store.add('Ana')">Add Ana</button>
  `,
})
export class App {
  protected readonly store = inject(NameStore);
}
Answers

1. The store keeps the writable signal private and hands out score with asReadonly():

// src/app/app.ts
import { Component, Service, computed, inject, signal } from '@angular/core';

@Service()
export class ScoreStore {
  private readonly scoreState = signal(0);

  readonly score = this.scoreState.asReadonly();
  readonly doubled = computed(() => this.score() * 2);

  add(points: number) {
    this.scoreState.update((n) => n + points);
  }

  reset() {
    this.scoreState.set(0);
  }
}

@Component({
  selector: 'app-score-buttons',
  template: `
    <button (click)="store.add(1)">+1</button>
    <button (click)="store.add(5)">+5</button>
    <button (click)="store.reset()">Reset</button>
  `,
})
export class ScoreButtons {
  protected readonly store = inject(ScoreStore);
}

@Component({
  selector: 'app-score-board',
  template: `<p>Score: {{ store.score() }}, doubled: {{ store.doubled() }}</p>`,
})
export class ScoreBoard {
  protected readonly store = inject(ScoreStore);
}

@Component({
  selector: 'app-root',
  imports: [ScoreButtons, ScoreBoard],
  template: `
    <app-score-board />
    <app-score-buttons />
  `,
})
export class App {}

Click +1 and +5. The page shows:

Score: 6, doubled: 12
+1+5Reset

2. @Service() makes one TallyStore for the whole app, so both panels inject the same one. Give each panel its own with providers:

// src/app/app.ts
import { Component, Service, inject, input, signal } from '@angular/core';

@Service()
export class TallyStore {
  private readonly countState = signal(0);
  readonly count = this.countState.asReadonly();

  add() {
    this.countState.update((n) => n + 1);
  }
}

@Component({
  selector: 'app-tally',
  providers: [TallyStore],
  template: `
    <p>{{ name() }}: {{ store.count() }}</p>
    <button (click)="store.add()">+</button>
  `,
})
export class Tally {
  readonly name = input.required<string>();
  protected readonly store = inject(TallyStore);
}

@Component({
  selector: 'app-root',
  imports: [Tally],
  template: `
    <app-tally name="Cats" />
    <app-tally name="Dogs" />
  `,
})
export class App {}

Click the first +. The page shows:

Cats: 1
+
Dogs: 0
+

3. Copy the array before sorting it, so the selector never touches the state:

// src/app/app.ts
import { Component, Service, computed, inject, signal } from '@angular/core';

@Service()
export class NameStore {
  private readonly namesState = signal(['Cy', 'Ben']);
  readonly names = this.namesState.asReadonly();
  readonly sorted = computed(() => [...this.names()].sort());

  add(name: string) {
    this.namesState.update((list) => [...list, name]);
  }
}

@Component({
  selector: 'app-root',
  template: `
    <p>Added: {{ store.names().join(', ') }}</p>
    <p>Sorted: {{ store.sorted().join(', ') }}</p>
    <button (click)="store.add('Ana')">Add Ana</button>
  `,
})
export class App {
  protected readonly store = inject(NameStore);
}

Click Add Ana. The page shows:

Added: Cy, Ben, Ana
Sorted: Ana, Ben, Cy
Add Ana

With this.names().sort() instead, the selector would sort the store’s own array. The “Added” line would come out sorted too, and the store’s state would have changed without any action being called.

What’s next

Our apps so far are one screen. In Part 16, we’ll add routes: several pages with their own URLs, links between them, route parameters read as inputs, and pages that load only when you visit them.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.