
Sharing State Without a Store Library: Signal-Based Services
- كاتب موثّق
- Angular 22
محتويات المقال
NotificationStore and read the same signal. The bug is one line: markRead() sets item.read = true on an object inside the signal's array, and the signal never finds out.
The common misconception
What actually happens
A root service is already shared
@Service(), Angular's shorthand for @Injectable({ providedIn: 'root' }), is provided in the root injector. The services guide lists what that guarantees: a single, shared instance for the whole application, available anywhere without registering a provider. Every component that calls inject(NotificationStore) gets the same object. Sharing was never the hard part.
Angular has to see the change
markForCheck(), a template event listener, or an update to a signal that a template reads. Assigning a plain field on a service is none of those, so the header has no reason to check itself again. Put the value in a instead, and every template or computed() that reads it is notified when it changes.
A signal only knows about new values
Object.is(), so it notices a new value, not a changed object. Mutating an item inside the array keeps the same array, so nothing is notified, and a computed() like the unread count keeps its cached result. The panel happened to re-render, because the click event checked it, which made the bug look like a sharing problem.
asReadonly() stops callers from calling set() or update(), but it has no mechanism to prevent deep mutation of the value. So the rule has to be explicit: every change creates a new array or object.
import { computed, Service, signal } from '@angular/core';@Service()export class NotificationStore { // Writable by every component that injects the store readonly items = signal<AppNotification[]>([]); readonly unread = computed( () => this.items().filter((n) => !n.read).length, ); markRead(id: string) { const item = this.items().find((n) => n.id === id); // Mutates in place: same array, so unread() never recomputes if (item) item.read = true; }}import { computed, Service, signal } from '@angular/core';@Service()export class NotificationStore { private readonly _items = signal<readonly AppNotification[]>([]); // Components can read these; only the methods below write readonly items = this._items.asReadonly(); readonly unread = computed( () => this._items().filter((n) => !n.read).length, ); add(notification: AppNotification) { this._items.update((items) => [notification, ...items]); } markRead(id: string) { this._items.update((items) => items.map((n) => (n.id === id ? { ...n, read: true } : n)), ); }}store.unread(), the panel reads store.items(), and both call store.markRead(id). There's one place where notifications change, and every change produces a new array that the signal can see.
Three rules make a store
One source of truth. The state lives in one private signal, the , and everything else is derived from it with computed().Read-only from outside. Components get asReadonly()signals and computed values, so they can't write past your methods.Changes through named methods. add()andmarkRead()are the only ways in, and each replaces the value instead of mutating it.
Scope it where it belongs
providers instead: the hierarchical injectors guide notes that each component instance then gets a private instance of the service, which is destroyed with the component. Use @Service({ autoProvided: false }) for a store that should only exist where you provide it.
asReadonly() makes the state immutable | set() and update(), not deep mutation |
How to apply it in your project
Find shared state in plain fields Look for root services with public mutable fields or arrays. Each one is a view that may not refresh under OnPush and zoneless change detection. Move it into a private signal Replace each field with a private signal(), expose it withasReadonly(), and turn derived values such as counts and totals intocomputed().Route every change through a method Search for writes from components, then give each kind of change a method that calls update()and returns a new array or object.Decide when a library earns its place If many teams change the same state through complex flows and need conventions or debugging tools to keep it manageable, evaluate a store library for that state. Keep the rest in signal services.
Key takeaways
A root-provided service is already a single instance that every component shares. Hold shared state in a private signal, expose it with asReadonly()andcomputed(), and change it through methods.Signals notice new values, not mutations, and asReadonly()doesn't stop deep mutation, so always replace the value.Provide a store in a component's providerswhen each instance needs its own copy.
التعليقات (0)