Sub topic 6
Providing services for a lazy route tree
This chapter assumes you can write standalone components, define routes with provideRouter, and read an ng build report. It also assumes you have seen loadChildren return a Routes array. Here you learn how to give a lazy feature area its own services, where those services live at runtime, and what goes wrong when you scope them carelessly.
Why scope services to a route tree
A service marked providedIn: 'root' is available everywhere. That is the right default for shared things like authentication or a settings store. Some services belong to one feature area only, such as an admin API client or a wizard's draft state. Scoping those services to the feature has two benefits:
- Lifetime and isolation. Only that area's components can inject the service. Other parts of the app get a clear error if they try, so dependencies stay visible.
- Bundle placement. The service class is imported only from the lazy area's files. The bundler places it in the lazy chunk, and visitors who never open the area never download it.
The second benefit is a property of imports, not of the providers array. We return to that in the pitfalls section.
The route `providers` property
Each route object accepts a providers array. When a route has one, the router creates an environment injector for that route. It is a child of the injector that was active when the route was matched. The injector serves the route and all of its descendants. The injector is created the first time the route is activated.
import { Injectable, signal } from '@angular/core';
@Injectable()
export class AdminService {
readonly visits = signal(0);
constructor() {
console.log('AdminService created');
}
recordVisit(): void {
this.visits.update(n => n + 1);
}
}The @Injectable() decorator has no providedIn. Without it, nothing registers the service automatically, so a provider must supply it. If you added providedIn: 'root' here, the route-level provider would be redundant and you would lose the scoping.
The lazy feature's route file registers the service:
import { Routes } from '@angular/router';
import { AdminService } from './admin.service';
import { AdminDashboardComponent } from './admin-dashboard.component';
import { AdminUsersComponent } from './admin-users.component';
export const ADMIN_ROUTES: Routes = [
{
path: '',
providers: [AdminService],
children: [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
],
},
];The wrapper route has an empty path and no component. It exists only to carry providers for its two children. This is a common pattern, and it adds no segment to the URL and no extra component to the DOM.
A component under it injects the service normally:
import { Component, inject } from '@angular/core';
import { AdminService } from './admin.service';
@Component({
selector: 'app-admin-dashboard',
standalone: true,
template: `<p>Dashboard visits: {{ admin.visits() }}</p>`,
})
export class AdminDashboardComponent {
protected readonly admin = inject(AdminService);
constructor() {
this.admin.recordVisit();
}
}The parent configuration points at the lazy file, as in the earlier chapters:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];The injector tree at runtime
The router builds a hierarchy of injectors. The lazy route's injector sits below the root environment injector. Lookups go upward, never downward.
Three consequences follow from this shape:
AdminDashboardComponentcan injectAdminServicefrom the admin injector. It can also injectAuthServicefrom the root, because lookups continue upward when a token is not found.HomeComponentcannot injectAdminService. Angular looks in the root injector, finds no provider, and throwsNullInjectorError: No provider for AdminService.- A root-provided service cannot inject
AdminServiceeither. The root injector cannot see its children.
Lifetime: one instance, kept after you leave
Open /admin, navigate to /, then return to /admin. The console shows AdminService created once, and the visit counter reads 2 on the second visit.
The router creates the route's injector once and keeps it on the route configuration. Leaving the route destroys the components but not the injector. The service instance, with its state, lives until the page reloads or the router configuration is replaced. Two practical results:
- State in a route-scoped service survives navigating away. This is useful for a filter or draft, but it surprises people who expect a fresh instance per visit.
- If you need a fresh instance on every visit, provide the service in the component's own
providersarray instead. A component-level provider belongs to the component's element injector and is destroyed with it.
import { Component } from '@angular/core';
import { WizardDraftService } from './wizard-draft.service';
@Component({
selector: 'app-wizard',
standalone: true,
providers: [WizardDraftService],
template: `<p>Wizard</p>`,
})
export class WizardComponent {}Nested providers and overriding
Providers can appear at several levels of one lazy tree. The nearest injector that has a provider for the token wins.
import { Routes } from '@angular/router';
import { ReportConfig, REPORT_CONFIG } from './report-config';
import { ReportListComponent } from './report-list.component';
import { ReportExportComponent } from './report-export.component';
export const REPORT_ROUTES: Routes = [
{
path: '',
providers: [{ provide: REPORT_CONFIG, useValue: { pageSize: 20 } satisfies ReportConfig }],
children: [
{ path: '', component: ReportListComponent },
{
path: 'export',
component: ReportExportComponent,
providers: [{ provide: REPORT_CONFIG, useValue: { pageSize: 500 } satisfies ReportConfig }],
},
],
},
];The supporting file defines the token:
import { InjectionToken } from '@angular/core';
export interface ReportConfig {
pageSize: number;
}
export const REPORT_CONFIG = new InjectionToken<ReportConfig>('REPORT_CONFIG');ReportListComponent sees pageSize: 20. ReportExportComponent sees pageSize: 500, because its own route creates a closer injector. Overriding is useful for configuration tokens. For stateful services it is a frequent source of confusion, because two components might silently hold two instances of what looks like one service.
Choosing where to provide a service
| Where | Instance lifetime | Visible to | Typical use |
|---|---|---|---|
| `providedIn: 'root'` | Whole app, created on first inject | Everything | Auth, settings, shared caches |
| Route `providers` | From first activation of the route until reload | That route and its descendants | Feature API clients, feature state |
| Component `providers` | One component instance | That component and its children | Per-visit drafts, form state |
Start with providedIn: 'root' for anything shared. Move a service down to route level when only one feature uses it and you want errors if someone else starts depending on it.
Where the bundler puts the code
A route-level provider controls which injector holds an instance. It does not move code between files. The chunk placement comes from the import graph:
- If only
admin.routes.tsand the admin components importAdminService, the class ends up in the lazy chunk. - If any eagerly loaded file imports
AdminService, even just to use it as a type, the bundler places the class in the main bundle. The instance is still scoped to the route, but the code ships to everyone.
Providing AdminService in ADMIN_ROUTES is safe because ADMIN_ROUTES is itself in the lazy chunk. Writing providers: [AdminService] in the root app.routes.ts would import the class into the main bundle, so do not do that for lazy-only services.
A providedIn: 'root' service used only by lazy code also lands in the lazy chunk. The tree-shakable provider is attached to the class, and the class is only imported from lazy files. So root scoping does not by itself pull code into the main bundle. The trade-off is visibility, not size.
Libraries and `importProvidersFrom`
Some libraries ship providers as NgModules. In a route's providers array you can include them with importProvidersFrom:
import { Routes } from '@angular/router';
import { importProvidersFrom } from '@angular/core';
import { ChartLibModule } from 'chart-lib';
import { ReportsHomeComponent } from './reports-home.component';
export const REPORT_ROUTES: Routes = [
{
path: '',
component: ReportsHomeComponent,
providers: [importProvidersFrom(ChartLibModule)],
},
];Here chart-lib stands for any third-party package that exposes an NgModule. Prefer a library's provideX() function when it has one. Use importProvidersFrom only for module-based APIs. Everything the module imports is pulled into the lazy chunk, which is the point of doing it here rather than in app.config.ts.
Common mistakes
- Provided in both places. Adding
providedIn: 'root'and a routeprovidersentry creates two instances. Components inside the route get the route's copy, and everything else gets the root copy. State appears to "reset" or diverge. Pick one. - Injecting a route-scoped service from outside. A
HomeComponent, a root service, or an eager guard that injectsAdminServicethrowsNullInjectorError. Move the service to root, or move the consumer into the route tree. - Importing the service eagerly. A file in the main bundle that references the class, even in a type annotation that is not elided, drags it into the main chunk. Check the build output, covered in a later chapter.
- Expecting a fresh instance per visit. Route injectors persist. Use component-level providers if you need per-visit state.
- Forgetting the wrapper route.
providersmust sit on a route object. If yourRoutesarray is a flat list of component routes, add a pathless parent route to carry the providers, as in the first example.
Summary
A route's providers array creates an environment injector for that route and its descendants. The injector is created on first activation and kept afterward, so instances persist across navigations. Lookups go upward only, so outside code cannot reach a route-scoped service. The bundler decides chunk placement from imports, so keep references to the service inside the lazy tree.
Exercise
You add providers: [ReportService] to the pathless parent route in REPORT_ROUTES, and ReportService also has @Injectable({ providedIn: 'root' }). A user opens /reports, goes to /, and returns to /reports. A component under /reports and the app's HeaderComponent both inject ReportService. How many instances exist, and which one does each component get?
Show answer
Two instances exist. The route provider creates one in the reports route injector, and providedIn: 'root' creates another in the root injector once something outside the route asks for it (here, HeaderComponent). The component under /reports gets the route injector's instance. HeaderComponent gets the root instance. The route's instance persists across the navigation away and back, so its state is kept. To get one shared instance, remove either the route provider or providedIn: 'root'.
Exercise
AdminService is provided in ADMIN_ROUTES and lives in admin.service.ts. A teammate adds import { AdminService } from './admin/admin.service'; to app.component.ts to read a type, and the main bundle grows. Why, and how do you fix it without changing the route providers?
Show answer
app.component.ts is in the main bundle, so the import makes the bundler include admin.service.ts there instead of only in the lazy chunk. The route-level provider still scopes the instance, but the class code now ships to every visitor. Remove the import from eager code. If AppComponent needs data from the admin area, move that logic into the lazy tree, or put a small interface or token in a shared file that both sides import and have AdminService implement it.