Sub topic 7
Scoping services to a route
This chapter assumes you can write standalone components and services, you have configured routes with provideRouter, and you know how inject() requests a dependency. It builds on the previous chapters on environment injectors and providedIn: 'root'.
Why scope a service to a route
A service with providedIn: 'root' is shared by the whole application. That suits an authentication service or an HTTP wrapper. It suits state that belongs to one feature less well. An admin area might hold a draft of unsaved settings, a selected tenant, or a cache of admin-only data. If that state lives in the root injector, it exists even when no admin page was ever opened, and any component can reach it.
Route-level providers address this. You list providers on a route, and Angular creates an environment injector for that route and registers them there. The service is then:
- shared by every component rendered under that route, including child routes,
- invisible to components outside it,
- created only when the route is first activated.
Declaring providers on a route
The providers property on a route takes the same provider forms as any other injector: class shorthand, useClass, useValue, useFactory and useExisting.
First, the service. It uses a plain @Injectable() with no providedIn, so it is not available anywhere until a provider list names it.
import { Injectable, signal } from '@angular/core';
@Injectable()
export class AdminSettingsService {
readonly compactTables = signal(false);
toggleCompactTables(): void {
this.compactTables.update(value => !value);
}
}Next, the route configuration, with a child route to show sharing:
import { Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { AdminUsersComponent } from './admin-users.component';
import { AdminSettingsService } from './admin-settings.service';
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [AdminSettingsService],
children: [{ path: 'users', component: AdminUsersComponent }],
},
];Both components ask for the service with inject():
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AdminSettingsService } from './admin-settings.service';
@Component({
selector: 'app-admin',
standalone: true,
imports: [RouterOutlet],
template: `
<button (click)="settings.toggleCompactTables()">Toggle compact tables</button>
<router-outlet />
`,
})
export class AdminComponent {
protected readonly settings = inject(AdminSettingsService);
}import { Component, inject } from '@angular/core';
import { AdminSettingsService } from './admin-settings.service';
@Component({
selector: 'app-admin-users',
standalone: true,
template: `<p>Compact tables: {{ settings.compactTables() }}</p>`,
})
export class AdminUsersComponent {
protected readonly settings = inject(AdminSettingsService);
}AdminComponent and AdminUsersComponent receive the same instance. Clicking the button in the parent changes what the child displays.
What Angular builds
When the router activates a route that has providers, it creates an EnvironmentInjector for that route. Its parent is the environment injector of the nearest ancestor route that has one, or the root environment injector if there is none.
The lookup for a component under admin goes through its element injectors first, as in the earlier chapters. If none of them provides the token, Angular moves to the environment injector for the component's route. That is the admin route injector. If the token is missing there too, the lookup continues to the root and then the platform injector. HomeComponent is not under the admin route, so its lookup never visits the admin route injector.
Lazy routes and feature-level providers
Providers on a route also apply to routes loaded lazily with loadChildren. The usual way to scope a whole feature is to put the providers on a parent route that loads a child route file:
import { Routes } from '@angular/router';
import { AdminSettingsService } from './admin/admin-settings.service';
export const routes: Routes = [
{
path: 'admin',
providers: [AdminSettingsService],
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];The child file exports an ordinary Routes array named ADMIN_ROUTES. Every route in it inherits the parent route's injector. The route file is downloaded when the user first navigates to /admin, and the injector is created at activation time.
Functional guards and resolvers declared on a route also run with inject() against the route's injector. A guard on admin can therefore read AdminSettingsService, because the injector that holds it is part of the guard's lookup chain.
Overriding a root service for one route
Route providers can shadow a token that exists higher up. Suppose LoggerService is providedIn: 'root' and logs to the console. You want the admin area to log to an audit endpoint:
import { Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { LoggerService } from './logger.service';
import { AuditLoggerService } from './audit-logger.service';
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [{ provide: LoggerService, useClass: AuditLoggerService }],
},
];Components under admin get AuditLoggerService when they inject LoggerService. Everything else gets the root implementation. Note that a root service which itself injects LoggerService still gets the root one, because the root injector resolves its dependencies from its own level and above. Providers declared lower in the tree never reach services created higher up.
Choosing a scope
| Scope | Declared with | Instances | Created when | Visible to |
|---|---|---|---|---|
| Root | `providedIn: 'root'` | One per application | First injected | Everything |
| Route | `providers` on a route | One per route injector | First injected under an activated route | Components, guards and resolvers under that route |
| Component | `providers` on a component | One per component instance | The component is created | That component and its descendants |
Choose the route scope when state should be shared by all pages of a feature but not by the rest of the app. Choose the component scope when each rendered instance needs its own state.
Pitfalls
- State survives navigation. The route injector is created on first activation and then kept with the route configuration. Navigating away from
/adminand back reuses the sameAdminSettingsServiceinstance, with its old state. Do not assume the service resets on navigation. If you want a reset, add an explicit method and call it from a guard or from the component'sngOnInit. If you want a fresh instance on every visit, use component-levelproviderson the routed component instead. - Components outside the route get
NullInjectorError. A service listed only in the admin route's providers cannot be injected byHomeComponentor by a shell component outside the router outlet. The error names the token and says no provider was found. - Duplicate instances. If a service is
providedIn: 'root'and also listed in a route'sproviders, the application has two instances. Components under the route see one, and everything else sees the other. This is sometimes the goal, but it is often an accident left from moving a service between scopes. RemoveprovidedInfrom services that should only live in a route. - Siblings do not share. Two separate routes that each list the same service in
providersget two instances. To share a service between sibling routes, provide it on their common parent route or at the root. - Route injectors are not element injectors. A component's own
providersstill win over a route's providers for that component, because element injectors are searched first.
Summary
The providers array on a route creates an environment injector for that route. All components under it share the instances it holds, and the rest of the app cannot see them. The injector is created on first activation and persists, so scoped state outlives navigation. Mixing a route provider with providedIn: 'root' for the same class produces two instances.
Exercise
A service DraftService is listed in the providers of the route path: 'editor'. The editor route has a child route path: 'preview'. A component on the unrelated route path: 'home' injects DraftService, and DraftService has no providedIn. What happens, and how do you change the setup so that home and editor share one instance?
Show answer
The home component throws a NullInjectorError, because its lookup goes through the root environment injector and never visits the editor route's injector. The preview child gets the editor route's instance. To share one instance between home and editor, provide the service in a scope both can see: add providedIn: 'root' to DraftService and remove it from the route's providers, or list it in providers of a common parent route. Do not keep it in both places, or two instances will exist.