Sub topic 7
Keeping feature state inside the feature
This chapter assumes you know Angular signals, inject(), and the route-level providers array from the previous chapter. The code uses Angular 17 or later (@if, @for, standalone components).
Why state belongs to the feature
State is the data a feature reads and changes while the user works with it: the loaded list of orders, the selected filter, a loading flag. If you keep it in a root-provided service, every part of the app can read and change it. That makes the feature's edges meaningless, because any other feature can reach in and depend on its internals.
Keeping state inside the feature gives you three things:
- Clear ownership. One class changes the orders. When the list is wrong, you know where to look.
- Lifetime tied to the feature. The store exists only where the feature's routes are active, and it is not part of the root injector.
- Smaller public surface. Other features see only what the barrel exports (a later chapter covers barrels). The store is not part of that surface unless you choose to export it.
A store is a plain service with signals
A feature store is an @Injectable() class that holds private writable signals and exposes read-only views of them. It does not need a state library. For most features, signals plus a few methods are enough.
// src/app/orders/data-access/order.model.ts
export interface Order {
id: string;
total: number;
shipped: boolean;
}// src/app/orders/data-access/orders.store.ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Order } from './order.model';
type LoadStatus = 'idle' | 'loading' | 'loaded' | 'error';
@Injectable()
export class OrdersStore {
private readonly http = inject(HttpClient);
private readonly _orders = signal<Order[]>([]);
private readonly _status = signal<LoadStatus>('idle');
private readonly _error = signal<string | null>(null);
readonly orders = this._orders.asReadonly();
readonly status = this._status.asReadonly();
readonly error = this._error.asReadonly();
readonly count = computed(() => this._orders().length);
readonly unshipped = computed(() => this._orders().filter((o) => !o.shipped));
load(): void {
if (this._status() === 'loading') {
return;
}
this._status.set('loading');
this._error.set(null);
this.http.get<Order[]>('/api/orders').subscribe({
next: (orders) => {
this._orders.set(orders);
this._status.set('loaded');
},
error: () => {
this._error.set('Could not load orders.');
this._status.set('error');
},
});
}
markShipped(id: string): void {
this._orders.update((list) =>
list.map((o) => (o.id === id ? { ...o, shipped: true } : o)),
);
}
}Three design choices matter here:
- No
providedIn. Without it, Angular does not register the class anywhere on its own. The route'sprovidersarray (shown in the previous chapter asproviders: [OrdersStore]) is the only place that creates it. - Private writable signals, public read-only signals.
asReadonly()returns a signal that has nosetorupdate. Components can read state but can only change it by calling store methods, so every change goes through code the feature owns. - Derived values use
computed.countandunshippedare recalculated only when_orderschanges. Do not store derived values in their own writable signals, because they can drift out of sync.
Using the store from feature components
Components in the feature inject the store the same way they inject any service.
// src/app/orders/feature/order-list.component.ts
import { Component, inject, OnInit } from '@angular/core';
import { OrdersStore } from '../data-access/orders.store';
@Component({
selector: 'app-order-list',
standalone: true,
template: `
@if (store.status() === 'loading') {
<p>Loading...</p>
}
@if (store.error(); as message) {
<p role="alert">{{ message }}</p>
}
<p>{{ store.count() }} orders, {{ store.unshipped().length }} not shipped</p>
<ul>
@for (order of store.orders(); track order.id) {
<li>
{{ order.id }}: {{ order.total }}
@if (!order.shipped) {
<button type="button" (click)="store.markShipped(order.id)">Ship</button>
}
</li>
}
</ul>
`,
})
export class OrderListComponent implements OnInit {
protected readonly store = inject(OrdersStore);
ngOnInit(): void {
this.store.load();
}
}The component holds no copy of the data. It reads signals from the store and calls its methods. If the detail route (:id) also injects OrdersStore, it gets the same instance, so the list and the detail view always agree.
Where the instance lives
The route configuration decides how long the store lives and who shares it.
When a component asks for OrdersStore, Angular looks in the component's own providers, then up through the route injectors, then in the root. Because OrdersStore is declared only in the orders route, the lookup succeeds for components under that route. It fails everywhere else.
Lifetime
A route's environment injector is created the first time the route is activated. In current Angular versions it is kept for the life of the app. As a result:
- Navigating from
/ordersto/customersand back does not recreate the store. The loaded orders are still there. - Your
load()call inngOnInitruns again on each return. If you want to skip the refetch, check the status first. If you want a fresh fetch, leave it as it is. - State does not reset on its own. If a feature must clear its data (for example on logout), add an explicit
reset()method and call it from the code that handles logout.
Sharing versus isolation
Where you put providers changes the sharing rules:
| Where the provider is declared | Instances | Lifetime |
|---|---|---|
| `providedIn: 'root'` on the class | One for the whole app | App lifetime |
| `providers` on a parent route with children | One shared by all child routes | Kept after first activation |
| `providers` on each sibling route | One per route, not shared | Kept after first activation |
| `providers` in a component's decorator | One per component instance | Destroyed with the component |
Use the parent-route form for a list and detail pair that share data. Use component-level providers for state that should vanish when the component goes away, such as a form wizard's draft.
Common errors
NullInjectorError: No provider for OrdersStore. A component outside the orders routes injected the store. This is the boundary working as intended. If the data is needed elsewhere, do not move the store to the root. Use one of the communication options from a later chapter.- Stale or duplicated data after adding a
providedIn: 'root'. If someone addsprovidedIn: 'root'to the store later, the class now has a root instance as well. Behavior depends on which injector answers first, which makes bugs hard to reproduce. Keep the decorator bare. - Two stores with the same data. Providing the store on both the parent route and a child route creates two instances. The list changes one and the detail view reads the other. Provide it once, on the highest route that needs it.
- Mutating arrays in place. Calling
pushon the array inside a signal does not notify readers, because the signal's value is the same reference. Always produce a new array or object withsetorupdate. - Exposing the writable signal. Making
_orderspublic lets any component callset. This defeats the ownership rule above.
When a signal store is not enough
A hand-written signal store suits a feature with one or two collections and a handful of actions. Consider a state library such as NgRx SignalStore when you need shared conventions across many teams, built-in entity helpers, or devtools-style tracing. The structure stays the same either way: the store is provided by the feature's route, and components talk to it through methods and read-only signals.
Exercise
A teammate adds providedIn: 'root' to OrdersStore "so the dashboard feature can show the order count." The route still lists providers: [OrdersStore]. Name two problems this creates, and describe a way to give the dashboard the count without making the store global.
Show answer
First, there are now two possible instances: the root one (used by the dashboard) and the route one (used by the orders components). They hold different data, so the dashboard count can disagree with the list. Second, any code in the app can now inject the store and call its methods, so orders state is no longer owned by the orders feature and the feature boundary is gone. To give the dashboard the count, remove providedIn: 'root' and have the orders feature export a small public API, for example a read-only orderCount signal provided through a dedicated service or an injection token that the orders feature exposes in its barrel. Alternatively, the dashboard can fetch its own count from the API endpoint. The dashboard then depends on the public API, not on the store.
Exercise
Add a reset() method to OrdersStore that returns it to its initial state. Then say when you would call it.
Show answer
Code: reset(): void { this._orders.set([]); this._status.set('idle'); this._error.set(null); }. Call it when the data must not outlive the user's session, for example from the logout handler. The route injector keeps the store after navigation, so leaving the orders route does not clear it.