Sub topic 5
Environment injectors: platform, root and beyond
This chapter assumes you know TypeScript classes and decorators, standalone components, how to write a basic service, and how route configuration looks. It covers the environment injector hierarchy: which injectors exist, who creates them, and how a lookup moves between them. The element injector tree, which follows the DOM, comes in a later chapter.
What an environment injector is
An environment injector holds providers that are configured outside any particular component template. You declare these providers in bootstrapApplication, in a route's providers array, in @Injectable({ providedIn: ... }), or in an NgModule. The injector creates each service lazily, the first time something asks for it. After that it caches the instance and returns the same one on every later request.
The word "environment" refers to the application environment, not to build settings such as environment.ts. The class is EnvironmentInjector, and you can inject it like any other dependency.
Each environment injector has a parent. A lookup starts in the injector closest to the requester. If that injector has no provider for the token, the request goes to its parent, and so on up the chain. The first injector that has a provider supplies the instance.
The levels of the hierarchy
From the top down, an Angular application normally has these environment injectors:
| Level | Created by | Typical contents |
|---|---|---|
| Null injector | Angular | Nothing. It throws `NullInjectorError` for every token. |
| Platform injector | `platformBrowser()` or `bootstrapApplication` | Services shared by every application on the page |
| Root environment injector | `bootstrapApplication(..., { providers })` | Application-wide services, `providedIn: 'root'` services |
| Route environment injector | The router, for a route with `providers` | Services scoped to a route subtree |
| Lazy NgModule injector | The router, when it loads a module | Providers from a lazy-loaded `NgModule` |
The null injector sits above everything. Reaching it means no injector in the chain had a provider, and it is the source of the error you will debug in a later chapter.
The platform injector
The platform injector is created before your application starts. It exists so that several Angular applications on one page can share a few things, such as the PlatformRef itself. Most applications have exactly one application, so you rarely put anything here.
You can add platform providers with the platformBrowser() call or with createPlatformFactory. For ordinary applications this is not necessary. If you want a service shared by the whole application, use the root injector instead. Putting a service on the platform makes it visible to every Angular application on the page, including ones you did not write.
The root environment injector
bootstrapApplication creates the root environment injector and fills it from three sources:
- The
providersarray in the second argument. - Providers collected from any
NgModuleyou import throughimportProvidersFrom. - Services that declare
providedIn: 'root', which register themselves the first time someone requests them.
Everything the application injects without a more specific provider ends up here. This is why a providedIn: 'root' service behaves as a singleton: one injector holds it, and every lookup that reaches this injector returns the same object.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes), provideHttpClient()],
});Functions named provideX, such as provideRouter and provideHttpClient, return a set of providers. They are the standard way to configure a library at the root. They return a value of type EnvironmentProviders, which Angular accepts only where an environment injector is being configured. That type prevents you from placing something like provideRouter(routes) in a component's providers array, where it would make no sense.
Overriding a default at the root
A token can carry a default factory, and the root providers can replace it. The API_URL example shows this:
import { InjectionToken } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
export const API_URL = new InjectionToken<string>('API_URL', {
providedIn: 'root',
factory: () => '/api',
});
bootstrapApplication(AppComponent, {
providers: [{ provide: API_URL, useValue: 'https://example.com/api' }],
});Both the token's default and the explicit provider live in the root environment injector. The explicit provider in bootstrapApplication wins, so inject(API_URL) returns 'https://example.com/api'. If you remove the providers entry, the factory supplies '/api'. A token with a default factory means the code that reads API_URL works in tests and small demos without any setup.
Route environment injectors
When a route declares providers, the router creates a child environment injector for that route. The parent is the injector of the enclosing route, or the root injector for top-level routes.
import { Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { AdminSettingsService } from './admin-settings.service';
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [AdminSettingsService],
},
];Three behaviors are worth knowing:
- The injector is created when the route is first activated, and it stays alive for the rest of the application. Navigating away and back reuses the same injector, so
AdminSettingsServicekeeps its state. - Components under the route, including child routes and their components, can inject the service. Components elsewhere in the app cannot, and they fall back to the root injector, where no provider exists.
- The route injector is also where
loadChildrenandloadComponentcode lands. If a lazy-loaded route file exports its ownproviders, those become part of this injector.
Because the injector is not destroyed on navigation, a route-scoped service is not a "per visit" service. If you need a fresh instance each time a component appears, use component providers, which a later chapter covers.
Seeing the chain from code
You can inspect where a service comes from by injecting EnvironmentInjector and asking it directly.
import { Component, EnvironmentInjector, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-probe',
standalone: true,
template: `<p>Has CounterService: {{ hasCounter }}</p>`,
})
export class ProbeComponent {
private readonly env = inject(EnvironmentInjector);
protected readonly hasCounter =
this.env.get(CounterService, null, { optional: true }) !== null;
}env.get(token, notFoundValue, options) walks the same chain as inject(), starting at that environment injector. Because CounterService is providedIn: 'root' (the earlier example), the call succeeds and creates the instance if it does not exist yet.
The injector you receive depends on where the code runs. A component under a route with providers receives that route's environment injector, and a component outside it receives the root one.
Creating an injector yourself
createEnvironmentInjector builds a child environment injector with a parent you choose. Use it for plugin-style code, or when you need to run code in a separate provider scope.
import { EnvironmentInjector, InjectionToken, createEnvironmentInjector, inject } from '@angular/core';
const GREETING = new InjectionToken<string>('GREETING');
export function greetInChildScope(): string {
const parent = inject(EnvironmentInjector);
const child = createEnvironmentInjector(
[{ provide: GREETING, useValue: 'hello from the child' }],
parent,
);
const value = child.get(GREETING);
child.destroy();
return value;
}Call greetInChildScope() from an injection context, such as a constructor or field initializer. The function injects the parent, builds the child, reads the token and destroys the child. Destroying an environment injector runs ngOnDestroy on the services it created. The router does this for the injectors it makes for lazy NgModules. You are responsible for it when you create one yourself.
Lifetime and destruction
The root environment injector lives as long as the application. Calling ApplicationRef.destroy() destroys it and calls ngOnDestroy on every service it instantiated. A providedIn: 'root' service is therefore never recreated during normal use.
A few details cause surprises:
- Instances are created lazily, so a root service that nothing injects is never constructed. Its constructor does not run at startup.
- To run code at startup, use
provideAppInitializer(or theAPP_INITIALIZERtoken) so it is explicit. - A service holds on to everything it references. A root singleton that stores component references or subscriptions leaks them until the application is destroyed.
NgModule injectors
An NgModule that is imported into the application contributes its providers to the injector that imports it. For the root, those go into the root environment injector. A lazy-loaded NgModule gets its own child environment injector when the router loads it. This is the older equivalent of route providers, and both end up as environment injectors in the same chain. A later chapter returns to this.
Choosing where to register a service
| Question | Choose |
|---|---|
| One shared instance for the whole app, tree-shakable | `providedIn: 'root'` |
| Needs configuration from the app author | A `provideX()` function used in `bootstrapApplication` |
| Shared only within one feature area, kept for the app's life | Route `providers` |
| Must be shared across several applications on a page | Platform providers (rare) |
Exercise
An application registers { provide: API_URL, useValue: 'https://example.com/api' } in bootstrapApplication. API_URL is also declared with providedIn: 'root' and a factory returning '/api'. A route shop lists nothing for API_URL. What does inject(API_URL) return inside a component under shop, and why?
Show answer
It returns 'https://example.com/api'. The route environment injector has no provider for the token, so the lookup moves to its parent, the root environment injector. The explicit provider from bootstrapApplication is registered there and takes precedence over the token's default factory.
Exercise
A service is declared providedIn: 'root', and the same class is also listed in the providers of the route admin. A component under admin and a component on the home page both inject it. How many instances exist, and which component gets which?
Show answer
Two instances. The component under admin finds the provider in the route environment injector first and gets that instance. The home page component finds no provider in its chain until the root injector, so it gets the root instance.