Sub topic 6
Scoping Services to a Feature Route
This chapter assumes you know TypeScript, Angular dependency injection, and the basics of the Angular Router. It shows how to give a feature its own service instance by registering the service on a route instead of in the root injector.
Why root-provided services are a problem for features
A service marked providedIn: 'root' is a single instance for the whole app. Any code can inject it, so a feature's internal store slowly becomes a shared dependency that other features rely on. It also stays in memory for the life of the app.
Route-level providers fix both problems. The service is created for the feature's routes, and only that part of the app can inject it.
Providing a service on a route
A route can declare a providers array. Angular creates an environment injector for that route and registers the listed services in 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 parent route with path: '' exists to hold the providers. Both child routes share that one injector, so the list and detail pages get the same OrdersStore instance.
Writing the service without providedIn
The store must not register itself in the root injector. Leave out providedIn.
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));
}
}With a bare @Injectable(), the service is only available where something provides it. If a component outside the orders routes injects it, Angular throws a NullInjectorError. That error is the boundary working as intended.
The store exposes orders through asReadonly(), so components can read the state but cannot change it. Only load() writes.
How the injector hierarchy works
Lookup goes upward only. A component asks its own injector first, then each parent, up to the root. OrdersStore sits in the orders injector, so the orders components find it. The customers components never see it, because a sibling injector is not on their path. HttpClient lives in the root, so every feature can still reach it.
Behavior to know about
- Lifetime. The route injector is created when the route is first activated. Angular keeps it while the route's code stays loaded, so the store's state usually survives navigating away and back. Do not rely on it being destroyed or reset.
- Resetting state. If you need fresh state on each visit, call a reset method from the component, or provide the service on the component with
providersin@Component. A component-level provider creates a new instance each time the component is created. - Lazy loading. A
providersarray on a lazily loaded feature's route file keeps the store out of the initial bundle's root injector. The code is loaded with the feature. - Shared data. If two features truly need the same instance, do not move the store to root by default. Expose a narrow service through the feature's public API, as the later chapters on barrels and cross-feature communication describe.
Common errors
| Symptom | Likely cause |
|---|---|
| `NullInjectorError: No provider for OrdersStore` | The component is outside the route that provides the store, or the route has no `providers` entry. |
| List and detail pages show different data | The store is provided separately on each child route instead of once on the shared parent. |
| State is still there after returning to the feature | The route injector stays alive. Add an explicit reset. |
Exercise
A teammate adds providedIn: 'root' to OrdersStore and keeps it in the orders route's providers array. What is lost, and where is the store instance used by the orders components created?
Show answer
The feature boundary is lost, because any code in the app can now inject OrdersStore without a NullInjectorError. The orders components get the instance from the route injector, since it is found first in the lookup path, while other code gets a separate root instance. That gives two instances and confusing, inconsistent state.
Exercise
You want the order detail page to start with empty state each time the user opens it. Name one approach that does not require moving the store to root.
Show answer
Provide a store on the detail component with providers in its @Component decorator, so a new instance is created each time the component is created. Alternatively, keep the route-level store and call a reset method when the component initializes.