Sub topic 7
Keeping Feature State Inside the Feature
This chapter assumes you know TypeScript, Angular signals at a basic level, dependency injection, and the Angular Router. It builds on route-scoped providers from the previous chapter.
Why state belongs to the feature
State is data that changes over time, such as a list of orders loaded from an API. If you put it in a global service, every feature can read and write it. That makes it hard to tell who changed a value, and the data stays in memory after the user leaves the feature.
A feature-level store is a service that holds one feature's state and exposes it through a small API. Only components inside that feature inject it. The route that owns the feature creates the store, so Angular can destroy it with the route.
A signal-based store
The store below has no providedIn setting. That means Angular cannot create it by itself. A route or component must list it in providers.
import { Injectable, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Order } from './order.model';
@Injectable()
export class OrdersStore {
private readonly http = inject(HttpClient);
private readonly _orders = signal<Order[]>([]);
readonly orders = this._orders.asReadonly();
readonly count = computed(() => this._orders().length);
load(): void {
this.http.get<Order[]>('/api/orders').subscribe((orders) => this._orders.set(orders));
}
}Three details matter here:
_ordersis private and writable. Only the store can change it.ordersis a read-only signal. Components can read it but cannot callseton it.countis a computed signal. It updates when_orderschanges, so no component has to recalculate it.
Providing the store on the route
The feature's route file lists the store in providers. Every child route can then inject it.
import { Routes } from '@angular/router';
import { OrdersStore } from './data-access/orders.store';
export const ORDERS_ROUTES: Routes = [
{
path: '',
providers: [OrdersStore],
children: [
{
path: '',
loadComponent: () =>
import('./feature/order-list.component').then((m) => m.OrderListComponent),
},
{
path: ':id',
loadComponent: () =>
import('./feature/order-detail.component').then((m) => m.OrderDetailComponent),
},
],
},
];The list and detail pages share one OrdersStore instance. The store is created when the user first navigates into the route, and it is not part of the root injector.
Using the store in a component
import { Component, OnInit, inject } from '@angular/core';
import { OrdersStore } from '../data-access/orders.store';
@Component({
selector: 'app-order-list',
standalone: true,
template: `
<h2>Orders ({{ store.count() }})</h2>
<ul>
@for (order of store.orders(); track order.id) {
<li>{{ order.id }}</li>
}
</ul>
`,
})
export class OrderListComponent implements OnInit {
protected readonly store = inject(OrdersStore);
ngOnInit(): void {
this.store.load();
}
}Common errors
NullInjectorError: No provider for OrdersStore. A component outside the route tried to inject the store, or the route forgotproviders. Fix the route, or move the component into the feature.- State resets unexpectedly. Route-provided services live as long as their route. If you want state to survive leaving the feature, you need a different scope. Do this on purpose, not by adding
providedIn: 'root'to avoid an error. - Exposing the writable signal. If you make
_orderspublic, any component can change it, and the store no longer controls its own data. - Reaching in from another feature. Importing
OrdersStoreinto the customers feature creates tight coupling. The chapter on cross-feature communication covers better options.
Exercise
A developer adds providedIn: 'root' to OrdersStore so a component in another feature can inject it. Name two problems this causes for the orders feature.
Show answer
The store is now part of the root injector, so it is no longer scoped to the orders route and its state can outlive the feature. Any feature can also read and call it, which couples the features together and hides who changes the data.