Sub topic 16
NgModule injectors and lazy-loaded modules
This chapter assumes you know environment injectors, providedIn: 'root', and route-level providers from the earlier chapters. It also assumes basic NgModule syntax. Most new code uses standalone components, but older code and many libraries still use modules. Their providers follow the same hierarchy rules.
Where NgModule providers go
An NgModule has no injector of its own in the element tree. Its providers array feeds an environment injector. Which one depends on how the module is loaded.
- Eagerly imported modules. When the root module, or a module in
bootstrapApplicationthroughimportProvidersFrom, imports another module, Angular merges that module's providers into the root environment injector. The module boundary disappears, and every provider is application-wide. - Lazy-loaded modules. A module loaded with
loadChildrengets its own child environment injector. Its parent is the root environment injector.
A lazy module with its own service
The module below lists ReportsService in its providers. Routes that load it with loadChildren create the child injector the first time the user navigates there.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ReportsComponent } from './reports.component';
import { ReportsService } from './reports.service';
const reportRoutes: Routes = [{ path: '', component: ReportsComponent }];
@NgModule({
imports: [ReportsComponent, RouterModule.forChild(reportRoutes)],
providers: [ReportsService],
})
export class ReportsModule {}import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'reports',
loadChildren: () => import('./reports/reports.module').then(m => m.ReportsModule),
},
];Components under reports find ReportsService in the lazy injector. Code outside that subtree cannot see it. Injecting it from, for example, the root injector throws NullInjectorError.
The duplicate-instance pitfall
Resolution walks from the child injector upward and stops at the first match. The lazy injector's own providers therefore shadow the root ones.
If the same service appears in an eagerly imported module and in a lazy module, the application has two instances. State saved in one is invisible to the other. This is the classic "my singleton is not a singleton" bug.
| Where the service is registered | Instances |
|---|---|
| `providedIn: 'root'` only | One, shared everywhere |
| Eager module `providers` only | One, in the root injector |
| Lazy module `providers` only | One, in the lazy injector |
| Eager and lazy module `providers` | Two |
To get a single shared instance, use providedIn: 'root' and remove the service from the lazy module's providers. To get one instance per lazy area, keep it in the lazy module or, in standalone code, in the route's providers.
Migrating toward standalone
A route with providers creates an environment injector like a lazy module does. You can usually replace a lazy NgModule with loadChildren pointing at a routes array.
import { Routes } from '@angular/router';
import { ReportsComponent } from './reports.component';
import { ReportsService } from './reports.service';
export const REPORT_ROUTES: Routes = [
{
path: '',
providers: [ReportsService],
children: [{ path: '', component: ReportsComponent }],
},
];When a standalone application must use providers from a library NgModule, wrap the module in importProvidersFrom(TheModule) and pass the result to bootstrapApplication or to a route's providers. The wrapper reads the module's providers and registers them in that environment injector.
Exercise
A service is listed in the providers of SharedModule. SharedModule is imported by AppModule and by the lazy OrdersModule. How many instances exist, and how do you reduce them to one?
Show answer
Two exist. The root injector has one from the eager import, and the lazy OrdersModule injector has its own copy. Mark the service @Injectable({ providedIn: 'root' }) and remove it from SharedModule's providers. Every injector then resolves to the single root instance.