Sub topic 6
Scoping Services to a Feature Route
This chapter assumes you know how Angular dependency injection resolves a service through an injector tree. It also assumes you can write a lazy route with loadChildren or loadComponent. Here you will see how the providers array on a route keeps a feature's services inside that feature, how long those services live, and which mistakes cause trouble.
Why not `providedIn: 'root'`
A service marked @Injectable({ providedIn: 'root' }) is registered in the root injector. Any code in the app can inject it, and there is only one instance. That suits an auth service or a logger. It does not suit an OrdersStore that only the orders feature should see.
Root-provided services cause three problems in a large app:
- Any feature can import and inject the store, so coupling grows without anyone deciding it should.
- The store is tree-shaken into the main bundle only if nothing else references it. In practice it often ends up outside the lazy chunk.
- State lives for the whole session, so stale data from one visit is still there on the next.
Route-level providers address all three. The service is registered in an injector that belongs to the feature's routes.
How route providers work
When a route config has a providers array, the router creates an environment injector for that route. Its parent is the injector of the enclosing route, or the root injector for top-level routes. The route's children and the components rendered by them resolve dependencies through it.
The injector is created the first time the route is activated, not at startup. Combined with loadChildren, a feature's code, its routes, and its services all arrive on first navigation.
A component in the customers subtree that injects OrdersStore fails, because lookup walks up through parents and never sideways.
Registering a store on a route
The service has no providedIn, so Angular cannot create it unless something provides it.
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));
}
}The feature route file provides it on a parent route with an empty path. That parent route adds no URL segment, but its injector covers every child.
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 now share one OrdersStore instance. The app-level routes only map the prefix:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
];Any component under /orders can inject the store:
import { Component, inject, OnInit } from '@angular/core';
import { OrdersStore } from '../data-access/orders.store';
@Component({
selector: 'app-order-list',
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();
}
}HttpClient comes from the root injector, which is where provideHttpClient() in the application config puts it. The route injector can reach it through its parent.
Choosing where to provide
| Location | Instances | Lifetime | Typical use |
|---|---|---|---|
| `providedIn: 'root'` or application config | One per app | Whole session | Auth, logging, app-wide settings |
| Route `providers` | One per route injector | From first activation, kept after navigating away | Feature stores, feature API clients |
| Component `providers` | One per component instance | Until that component is destroyed | Form state, a wizard step, a widget |
If a feature store should reset every time the user opens the feature, component-level providers on the feature's shell component may fit better than route providers.
Lifetime and stale state
The route injector is not destroyed when the user leaves the route. Navigate from /orders to /customers and back, and you get the same OrdersStore with the same data. This is often useful because it works as a cache. It also surprises people who expect a fresh store.
You have three common ways to handle it:
- Call
load()inngOnInitof the entry component, as above, so every visit refreshes the data. The old data stays visible until the response arrives. - Add a
reset()method that clears the signals, and call it from a route guard or the component'sngOnDestroy. - Move the provider to a shell component's
providersarray so the store dies with the component.
Common errors
NullInjectorError outside the feature
The fix is not to move the provider to root. If two features need the same data, see the chapter on communication between features. Usually the answer is a small shared service in a core or data-access layer, exposed on purpose.
Two instances of the same service
If a service is provided in two places, each injector creates its own instance. A component sees whichever one is closest. Suppose you add providers: [OrdersStore] to a route and also list OrdersStore in app.config.ts. The route's components get the route copy, and everything else gets the root copy. The two do not share state, and bugs appear as data that is "sometimes missing".
Provide each service in exactly one place. Searching for the class name across providers arrays is a quick check.
Providing on the wrong route
providers on a leaf route with loadComponent is visible only to that component and its children. Provide on a parent route when siblings must share the instance, as OrdersStore does for the list and detail pages. Putting providers: [OrdersStore] on each child route gives each page its own store.
Injecting the store in a guard or resolver
Guards and resolvers run in the injection context of the route they belong to. A guard attached to a child of the providing route can inject the store. A guard attached to the parent route that holds the providers can too, but a guard on a sibling cannot.
Testing a route-scoped store
Because the store has no providedIn, a test must provide it. That also makes tests independent of the route setup.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { OrdersStore } from './orders.store';
import { Order } from './order.model';
describe('OrdersStore', () => {
let store: OrdersStore;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [OrdersStore, provideHttpClient(), provideHttpClientTesting()],
});
store = TestBed.inject(OrdersStore);
http = TestBed.inject(HttpTestingController);
});
it('stores the orders returned by the API', () => {
store.load();
http.expectOne('/api/orders').flush([{ id: '1' }] as Order[]);
expect(store.count()).toBe(1);
});
});Summary of the working rules
- Omit
providedInon feature services so they cannot leak into other features. - Provide on the feature's parent route so all its pages share one instance.
- Remember that the instance outlives navigation and plan refresh or reset behavior.
- Provide each service in one place only.
Exercise
A user opens /orders, loads 50 orders, goes to /customers, and returns to /orders. OrdersStore is provided in the providers array of the orders parent route. Does the store still hold the 50 orders, and what are two ways to make the list start empty on each visit?
Show answer
Yes. The route injector is created on first activation and is not destroyed when the user leaves, so the same OrdersStore instance and its signals are reused. To start empty on each visit, either add a reset() method that clears the signal and call it from a guard or the component's ngOnDestroy, or move the provider to the providers array of a shell component so the store is destroyed with that component.
Exercise
A header component in the app shell injects OrdersStore to show an order count and throws NullInjectorError. Why does this happen, and why is adding providers: [OrdersStore] to the root application config a poor fix?
Show answer
The header is not in the orders route subtree, so its injector chain (shell, then root) never includes the orders route injector, and lookup does not go sideways or downward. Providing the store at root would create a separate instance from the one the orders routes use if they also provide it, so the two would not share state. It would also remove the feature's boundary. A better fix is to expose the needed data through a small shared service that both the shell and the feature use.