Sub topic 16
NgModule injectors and lazy-loaded modules
This chapter assumes you know how root, route and element injectors resolve a dependency, as covered in the earlier chapters. It also assumes you can read an NgModule declaration and a loadChildren route. Standalone components are the modern default. Many existing applications still contain NgModules, though, and their provider rules decide whether a service is shared or duplicated.
Where NgModule providers end up
An NgModule is not an injector. Its providers array is a list of providers, and Angular adds that list to an environment injector. Which injector receives it depends on how the module is loaded.
| How the module is loaded | Injector that receives its providers |
|---|---|
| Imported by the root module or by `importProvidersFrom` in `bootstrapApplication` | The root environment injector |
| Imported by another eagerly loaded module | The same root environment injector, merged in |
| Loaded with `loadChildren` returning an NgModule | A new child environment injector created for that route |
Eagerly imported modules are flattened. Angular walks the whole imports graph of the root module and registers every provider in one injector. After that, it makes no difference which module declared a provider, and every component and service in the eager part of the app sees it.
A lazy module is different. When the router loads it, Angular creates a new environment injector whose parent is the injector of the route that loaded it, usually root. The providers of the lazy module and of everything it imports go into that child injector.
The lazy module example
Define a service and a module that lists it in providers.
import { Injectable } from '@angular/core';
@Injectable()
export class ReportCache {
readonly createdAt = Date.now();
readonly entries = new Map<string, unknown>();
}import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ReportsComponent } from './reports.component';
import { ReportCache } from './report-cache';
const routes: Routes = [{ path: '', component: ReportsComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
providers: [ReportCache],
})
export class ReportsModule {}Then load the module lazily from the application routes.
import { Routes } from '@angular/router';
export const appRoutes: Routes = [
{
path: 'reports',
loadChildren: () =>
import('./reports/reports.module').then(m => m.ReportsModule),
},
];ReportCache is created in the lazy injector the first time something asks for it under /reports. Code outside that route cannot inject it. A component elsewhere that calls inject(ReportCache) throws NullInjectorError, because the lookup climbs only through ancestors and the lazy injector is a sibling branch.
The injector also survives navigation. After the user leaves /reports and comes back, the router reuses the same lazy injector, so ReportCache keeps its state. Angular does not destroy the module injector when the route is deactivated.
Duplicate instances: the classic pitfall
Suppose AuthState is listed in the providers of both AppModule and ReportsModule. There are now two providers for the same token in two injectors. Components in the lazy part resolve to the lazy copy because it sits closer. Everything else gets the root copy. The state is split, and nothing reports an error.
The usual fixes are these:
- Make the service
@Injectable({ providedIn: 'root' })and remove it from every module'sproviders. It is then created once in the root injector. A lazy module can still inject it, because root is an ancestor. - Keep the provider in a module only when you intend a separate instance per lazy feature. Add a comment saying so.
A well-known variant involves modules that bring providers with them, such as the old HttpClientModule. If a lazy module imports it, Angular registers a new HttpClient stack in the lazy injector. That stack does not see the interceptors configured at root. Import such modules once, at the root. In current Angular, prefer provideHttpClient(), which belongs in the root providers only.
Provider order inside one injector
Within a single environment injector, Angular processes providers in a fixed order. Providers from imported modules are registered first, in import order. Then the declaring module's own providers are registered. When two providers use the same token, the last one registered wins. That is why a module can override a provider it gets from an import.
import { NgModule } from '@angular/core';
import { API_URL } from './tokens';
import { SharedModule } from './shared.module';
@NgModule({
imports: [SharedModule], // may also provide API_URL
providers: [{ provide: API_URL, useValue: 'https://reports.example.com' }],
})
export class ReportsModule {}Here ReportsModule wins over SharedModule for API_URL inside the lazy injector. Root keeps its own value for everything outside the route.
Module constructors run once per injector
An NgModule class can take dependencies in its constructor. Angular instantiates it when the injector that owns it is created, so the constructor runs once for the root injector and once for each lazy module injector.
import { NgModule, inject } from '@angular/core';
import { ReportCache } from './report-cache';
@NgModule({ providers: [ReportCache] })
export class ReportsModule {
constructor() {
const cache = inject(ReportCache);
console.log('Reports injector created at', cache.createdAt);
}
}This is a handy way to see when a lazy injector is created. The message appears the first time the route loads and does not appear on later visits. Do not use module constructors for heavy setup in new code. Prefer provideAppInitializer at the root, or ENVIRONMENT_INITIALIZER for a route-scoped hook.
Bridging to standalone code
You do not need to convert a module-based library before using it from a standalone application. importProvidersFrom extracts the providers of an NgModule and any modules it imports, and returns them as environment providers.
import { bootstrapApplication } from '@angular/platform-browser';
import { importProvidersFrom } from '@angular/core';
import { AppComponent } from './app/app.component';
import { LegacyAnalyticsModule } from './app/legacy-analytics.module';
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(LegacyAnalyticsModule)],
});The same function works in a route's providers, so the module's providers land in that route's environment injector rather than in root. Routes that load standalone children behave like lazy modules for injection purposes. A loadChildren that returns a Routes array with providers on the parent route gets its own environment injector, as in the route-provider chapter.
Do not call importProvidersFrom on a module and then also import it in a component's imports. Only the root or route placement counts for providers.
Diagnosing a lazy injector problem
When a lazy feature behaves strangely, check these in order:
- Find every place the token appears in a
providersarray or in an imported module. More than one place across root and lazy parts means more than one instance. - Check that the service has
providedIn: 'root'when it should be a singleton. - Log a value from the instance, such as the
createdAtfield above. Compare it between an eager component and a lazy one. - If you get
NullInjectorErrorfor a service that a lazy module provides, check whether the failing code runs outside the route, for example in a root-level component.
Summary
- Eager NgModule providers merge into the root environment injector, so module boundaries do not matter there.
- A lazy-loaded NgModule gets its own child environment injector, which holds its providers and those of its imports.
- Listing the same token in root and lazy providers creates two instances.
providedIn: 'root'avoids this. - Inside one injector, imports register first and the declaring module's own providers register last, so the last one wins.
importProvidersFromlets standalone code and routes use providers from NgModules.
Exercise
AppModule lists CartService in providers, and the lazy CheckoutModule also lists CartService in providers. A header component in the root app adds an item, and the checkout page shows an empty cart. Explain why this happens and give two ways to fix it.
Show answer
The two modules register CartService in two different injectors. AppModule's provider goes into the root environment injector, and CheckoutModule's goes into the lazy module's child injector. The header gets the root instance, while checkout components find the closer lazy instance first, so they see two separate carts. Fix it by removing CartService from both providers arrays and marking it @Injectable({ providedIn: 'root' }). The other fix is to remove it from CheckoutModule only, so that lazy components fall through to the root provider.
Exercise
A lazy module's service is listed only in that module's providers. A component in the root app calls inject(ReportCache). What happens, and why?
Show answer
Angular throws NullInjectorError. The root component's lookup goes through its element injectors and then the root and platform environment injectors. The lazy module's injector is a child of root, not an ancestor of the component, so it is never searched.