Sub topic 6
Providing services for a lazy route tree
This chapter assumes you can write standalone components, define routes with provideRouter, and use inject(). You should also have seen loadChildren from the previous chapter. Here you will learn how to give a lazy feature area its own services, and what that does to the bundle and to service lifetime.
Where the route `providers` property fits
A Route can have a providers array. When the router first activates that route, it creates an environment injector for it. This injector is a child of the injector that was active at that point, usually the root environment injector. The route's component, its child routes, and everything those components inject can see the services in the array.
Services listed this way are not registered at application start. They are created only after the user reaches the route.
When a component asks for a token, Angular looks in the route injector first and then moves up to the root. A service in the route injector is therefore found by every component in that route tree. Root-level code cannot see it.
A worked example
Start with a service that has no providedIn setting. It is only available where someone lists it in a providers array.
import { Injectable, signal } from '@angular/core';
@Injectable()
export class AdminService {
readonly selectedUserId = signal<string | null>(null);
select(id: string): void {
this.selectedUserId.set(id);
}
}Next, register it on the top route of the lazy area.
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 providers entry sits on a component-less parent route with path: ''. This is a common pattern. It scopes the service to the whole area without adding a URL segment. Any component under it can then inject the service.
import { Component, inject } from '@angular/core';
import { AdminService } from './admin.service';
@Component({
selector: 'app-admin-users',
template: `<p>Selected: {{ admin.selectedUserId() ?? 'none' }}</p>`,
})
export class AdminUsersComponent {
protected readonly admin = inject(AdminService);
}AdminDashboardComponent that injects AdminService receives the same instance. Both components share state, and no other part of the app can reach it.
Why this keeps code out of the main bundle
The bundler follows static imports. admin.service.ts is imported only by admin.routes.ts and the admin components, and those are reached only through a dynamic import(). So the service ends up in the lazy chunk.
A service declared with providedIn: 'root' follows the same rule if only lazy code imports it. The bundler places it in the lazy chunk, and the root injector creates it on first use. The difference is scope. A root service is a singleton for the whole app once created. A route-level service has an instance tied to that route's injector.
Lifetime and sharing
- The route injector is created once per route configuration, on first activation.
- It is not destroyed when the user navigates away. Returning to the area reuses the same service instance and its state.
- Two separate route entries that each list
AdminServiceget two separate instances. - If a root-level service also provides the same token, the route-level one shadows it for components inside the route tree.
<br>
Summary of choices
| Need | Approach |
|---|---|
| State shared inside one feature area only | `providers` on the area's parent route |
| App-wide singleton used mostly by lazy code | `providedIn: 'root'`, imported only from lazy files |
| Fresh instance per component | `providers` in the `@Component` decorator |
Exercise
A service ReportCache is listed in providers on the reports route, and a component in the main bundle injects it. What happens when that component is created, and why?
Show answer
Injection fails with a "No provider" error (NullInjectorError). The route injector is a child of the root injector, so eager components that sit outside the route tree cannot see its providers. The component's static import of ReportCache would also pull the service into the main bundle. To fix both problems, provide the service in the root injector or move the component into the route tree.