Sub topic 10
Sharing State Through Services
Earlier chapters showed how Angular creates a service and hands it to consumers. This chapter covers what happens when that service holds data that several components read and change. It assumes you know TypeScript classes and generics, how inject() works, what providedIn: 'root' means, and the basics of the injector hierarchy. Some familiarity with Angular signals or RxJS Observables helps, but each API is explained when it first appears.
Why State Lives in Services
Components are created and destroyed as the user navigates. A component field only lasts as long as the component does, and other components can't reach it unless you pass the data through inputs and outputs. When two distant parts of the page need the same data, such as a cart badge in the header and a cart list on a checkout page, wiring inputs and outputs through every component in between gets brittle quickly.
A service gives the state one owner. The injector creates one instance for its scope, and every consumer that asks for the token gets that same instance. If the service lives in the root injector, the state outlives any single component and every component reads the same copy.
This only helps if the service follows three rules:
- One writer. Only the service changes the state, through named methods.
- Read-only exposure. Consumers get a value they can read and react to but cannot assign.
- Change notification. When the state changes, consumers find out without polling.
Signals and RxJS subjects both cover the third rule. Exposing a read-only view covers the second, and keeping the writable handle private covers the first.
A Signal-Based Store
A signal is a wrapper around a value that tells Angular when the value changes. You read it by calling it, as in todos(). You write it with set() or update(). A computed signal derives its value from other signals and recalculates only when they change.
import { Injectable, computed, signal } from '@angular/core';
export interface Todo {
id: number;
title: string;
done: boolean;
}
@Injectable({ providedIn: 'root' })
export class TodoStore {
private readonly _todos = signal<Todo[]>([]);
private nextId = 1;
readonly todos = this._todos.asReadonly();
readonly remaining = computed(() => this._todos().filter(t => !t.done).length);
add(title: string): void {
const trimmed = title.trim();
if (!trimmed) {
return;
}
const todo: Todo = { id: this.nextId++, title: trimmed, done: false };
this._todos.update(list => [...list, todo]);
}
toggle(id: number): void {
this._todos.update(list =>
list.map(t => (t.id === id ? { ...t, done: !t.done } : t))
);
}
remove(id: number): void {
this._todos.update(list => list.filter(t => t.id !== id));
}
}asReadonly() returns a Signal<Todo[]> without set or update, so a consumer can't write store.todos.set([]). The state can only change through add, toggle, and remove, and those are the places to put validation such as rejecting empty titles.
Several components can now share the store without knowing about each other:
import { Component, inject } from '@angular/core';
import { TodoStore } from './todo.store';
@Component({
selector: 'app-todo-input',
standalone: true,
template: `
<input #title />
<button (click)="store.add(title.value); title.value = ''">Add</button>
`
})
export class TodoInputComponent {
protected readonly store = inject(TodoStore);
}
@Component({
selector: 'app-todo-list',
standalone: true,
template: `
@for (todo of store.todos(); track todo.id) {
<li>
<input type="checkbox" [checked]="todo.done" (change)="store.toggle(todo.id)" />
{{ todo.title }}
<button (click)="store.remove(todo.id)">x</button>
</li>
}
`
})
export class TodoListComponent {
protected readonly store = inject(TodoStore);
}
@Component({
selector: 'app-todo-count',
standalone: true,
template: `{{ store.remaining() }} left`
})
export class TodoCountComponent {
protected readonly store = inject(TodoStore);
}When TodoInputComponent calls add, the private signal changes. The remaining computed signal becomes stale, and Angular re-renders the templates that read todos() or remaining(). No component subscribes or unsubscribes by hand.
The Immutability Rule
Signals compare the old and new value with Object.is by default. If you change an array in place and then set the same reference, the signal sees no change and nothing re-renders.
// Wrong: mutates in place; the reference is unchanged, so no notification.
this._todos().push(todo);
this._todos.set(this._todos());
// Right: produce a new array.
this._todos.update(list => [...list, todo]);The same applies to objects inside the array. toggle above builds a new object with { ...t, done: !t.done } rather than assigning t.done = !t.done. Writing t.done = true directly would change data that templates already rendered, without any notification, and the screen would show the old value until something else happened to trigger a re-render.
An RxJS-Based Store
Before signals, the usual tool was a BehaviorSubject. A subject is an Observable you can push values into. A BehaviorSubject also keeps the current value and replays it to each new subscriber. That replay matters for state: a component that subscribes late still gets the current value right away.
import { Injectable } from '@angular/core';
import { BehaviorSubject, map } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class NotificationStore {
private readonly messagesSubject = new BehaviorSubject<string[]>([]);
readonly messages$ = this.messagesSubject.asObservable();
readonly count$ = this.messages$.pipe(map(list => list.length));
push(message: string): void {
this.messagesSubject.next([...this.messagesSubject.value, message]);
}
clear(): void {
this.messagesSubject.next([]);
}
}asObservable() plays the same role as asReadonly(): it hides next() from consumers. The immutability rule still matters here, because consumers that use OnPush change detection or distinctUntilChanged compare references.
Consumers can use the async pipe, or turn the stream into a signal with toSignal, which also handles unsubscribing when the component is destroyed:
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NotificationStore } from './notification.store';
@Component({
selector: 'app-notification-bell',
standalone: true,
template: `
<span>{{ count() }}</span>
<button (click)="store.clear()">Clear</button>
`
})
export class NotificationBellComponent {
protected readonly store = inject(NotificationStore);
protected readonly count = toSignal(this.store.count$, { requireSync: true });
}requireSync: true tells toSignal that the source emits synchronously on subscribe. That holds for anything derived from a BehaviorSubject, so the signal's type is number rather than number | undefined. toSignal calls inject() internally, so it must run in an injection context, such as a field initializer.
Choosing a Subject Type
| Type | Holds current value | New subscriber receives | Fit for shared state |
|---|---|---|---|
| `Subject` | No | Only future emissions | Poor: late subscribers see nothing |
| `BehaviorSubject` | Yes (requires initial value) | Latest value, then future | Good default |
| `ReplaySubject(1)` | Yes, after first emission | Latest value once one exists | Useful when there's no sensible initial value |
A plain Subject works for events, such as "user logged out". It doesn't work for state.
Signals or RxJS?
| Concern | Signals | RxJS subjects |
|---|---|---|
| Synchronous current value | Always: `state()` | `BehaviorSubject.value`, or subscribe |
| Derived values | `computed`, memoized and lazy | `map`, `combineLatest`, recomputed per subscriber unless shared |
| Cleanup in components | None needed | `async` pipe, `toSignal`, or `takeUntilDestroyed` |
| Time-based or async flows (debounce, retry, cancel) | Awkward on their own | Built for it |
| Template integration | Direct call in templates | `async` pipe or conversion |
A common split is to keep state in signals and use RxJS for the async work that feeds it, such as HTTP calls, debounced search, or websockets. The toSignal and toObservable functions connect the two.
Side Effects on State Changes
Sometimes a state change should trigger work outside Angular, such as saving to localStorage. An effect runs whenever the signals it reads change. Create it in the service constructor, which is an injection context:
import { Injectable, effect, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeStore {
private readonly _theme = signal<'light' | 'dark'>(
(localStorage.getItem('theme') as 'light' | 'dark' | null) ?? 'light'
);
readonly theme = this._theme.asReadonly();
constructor() {
effect(() => {
localStorage.setItem('theme', this._theme());
});
}
toggle(): void {
this._theme.update(t => (t === 'light' ? 'dark' : 'light'));
}
}Use effects for syncing state to the outside world. Don't use an effect to copy one signal into another. Use computed for that, because it stays consistent and avoids extra change-detection passes.
Scope Decides Who Shares
A store class doesn't decide whether its state is global. The provider does. With providedIn: 'root', the whole application shares one instance. If a component also lists the store in its providers, that component and its subtree get a separate instance with separate state. That's useful for something like one draft per editor panel.
It's also the most common cause of "my update doesn't show up". If one component lists TodoStore in providers by mistake, that component writes to a private copy and the rest of the app never sees the change.
Common Errors
- Mutating in place.
push,splice, or assigning to a property of shared state skips change notification. Always produce new references. - Exposing the writable handle. A public
signalorBehaviorSubjectlets any component write state, and invariants then break in places that are hard to trace. - Using
Subjectfor state. Components created after an emission render nothing until the next one. - Manual subscriptions without cleanup. Calling
subscribe()on a root store from a component keeps the component alive after it's destroyed. PrefertoSignal, theasyncpipe, ortakeUntilDestroyed(). - Effects that write signals. These create update loops and wasted work. Derive values with
computedinstead. - Accidental component providers. These create isolated copies of what should be global state.
Exercise
A teammate writes markDone(id: number) { const t = this.todos().find(x => x.id === id); if (t) { t.done = true; } this.todos.set(this._todos()); }. The checkbox in TodoListComponent doesn't update and remaining() stays the same. Explain why and rewrite the method.
Show answer
The method changes the existing object in place and then sets the same array reference. Signals compare values with Object.is, so set() sees no change, notifies no one, and remaining() stays stale. Rewrite it to produce new references: markDone(id: number) { this._todos.update(list => list.map(t => t.id === id ? { ...t, done: true } : t)); }
Exercise
NotificationStore is provided in root. A SettingsPanelComponent declares providers: [NotificationStore] and calls push('Saved'). The header's NotificationBellComponent never shows the new count. What is happening, and how do you fix it?
Show answer
The component-level provider makes the element injector create a second NotificationStore for SettingsPanelComponent and its children. push() writes to that private instance, while the header reads the root instance. Remove NotificationStore from the component's providers so both components resolve the root instance.
Exercise
You need a search store where the query text is shared state, but results must be fetched with a 300 ms debounce and in-flight requests cancelled when the query changes. Which parts would you model with signals and which with RxJS?
Show answer
Keep the query (and the latest results) in signals, because they are current-value state that templates read. Convert the query to an Observable with toObservable, then apply debounceTime(300) and switchMap to the HTTP call; switchMap cancels the previous request. Convert the result stream back with toSignal, or write it into a private results signal. RxJS handles the time-based, cancellable async flow, and signals hold the state.