Sub topic 5
Environment injectors: platform, root and beyond
This chapter assumes you know what a provider and an injection token are, and that you can write a standalone component and a route configuration. It covers the first of Angular's two injector hierarchies.
What an environment injector is
An environment injector is an injector that is not tied to a DOM element. Angular builds these injectors from configuration: bootstrap options, route definitions and providedIn metadata. Each one has a parent, so together they form a chain.
A lookup starts at the bottom and moves up one parent at a time. If it reaches the null injector, Angular throws NullInjectorError.
Platform and root
The platform injector sits above every application. Angular creates it once per page. It holds services that all applications on the page share, such as PlatformRef. You rarely add to it. A service can opt in with providedIn: 'platform'. Use that only when several Angular applications on one page must share state.
The root environment injector belongs to one application. It holds:
- every provider passed to
bootstrapApplication - every service declared with
providedIn: 'root' - providers added through
importProvidersFromorprovideRouter
Services registered here are singletons for that application.
import { InjectionToken } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
export const FEATURE_FLAGS = new InjectionToken<string[]>('FEATURE_FLAGS');
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
{ provide: FEATURE_FLAGS, useValue: ['beta-search'] },
],
});Everything in that providers array lands in the root environment injector. Any component, directive or service in the application can inject FEATURE_FLAGS.
Going beyond root
Root is the main environment injector, but it is not the only one. Angular creates child environment injectors in these cases:
- A route with a
providersarray gets its own injector. Its parent is the injector of the enclosing route, or root for top-level routes. - A lazy-loaded NgModule gets its own injector.
- Your own code can call
createEnvironmentInjector.
The last case is useful when you create something dynamically and want a short-lived scope for it:
import {
createEnvironmentInjector,
EnvironmentInjector,
inject,
Injectable,
} from '@angular/core';
@Injectable()
export class WizardState {
step = 1;
}
export function createWizardScope(): EnvironmentInjector {
const parent = inject(EnvironmentInjector);
return createEnvironmentInjector([WizardState], parent);
}Call createWizardScope() in an injection context, such as a field initializer or a constructor. The returned injector can resolve WizardState, and it falls back to its parent for everything else. Call destroy() on it when the scope ends. That runs ngOnDestroy on the services it created.
Choosing where to provide
| Need | Where to provide |
|---|---|
| One instance for the whole application | `providedIn: 'root'` |
| A value configured at startup | `bootstrapApplication` providers |
| One instance per route subtree | The route's `providers` |
| Shared across several applications on one page | `providedIn: 'platform'` |
Prefer providedIn: 'root' by default. Angular can remove an unused root service from the bundle, which it cannot do for a service listed in a providers array.
Exercise
A service is listed in the providers of a route /reports. A root-level service that is providedIn: 'root' injects it. What happens, and why?
Show answer
Angular throws NullInjectorError. The root-level service resolves against the root environment injector. The route's provider lives in a child environment injector, and lookups only move up to parents, never down to children.