Full answer
Besides the root injector, Angular has environment injectors that are created for parts of the app.
Route providers:
{ path: 'checkout', providers: [CartDraftService], children: [...] }
The router creates an environment injector for this route and its children, as a child of the injector of the parent route (or root). CartDraftService is created when first injected, shared by all components in these routes, and destroyed when the route is deactivated for good (its ngOnDestroy runs). Benefits: state scoped to a flow (checkout, wizard), lazy loaded features that bring their own services, and different configuration per area (for example a different API_URL token for the admin area). With loadChildren the providers also arrive with the lazy chunk.
Run-time injectors:
createEnvironmentInjector(providers, parentInjector)makes an injector from providers. Use it for plugin-like or dialog-like features that need their own services. Pass it tocreateComponent(Component, { environmentInjector })or toViewContainerRef.createComponent. Destroy it withinjector.destroy()when done, which runsngOnDestroyof its services.runInInjectionContext(injector, () => inject(Service))runs a function with an injector active, so functions that callinject()can be used outside constructors, for example in a callback or a test.EnvironmentInjectoritself can be injected, andinject(EnvironmentInjector).get(Token)is the safe service locator for rare cases.
Lookup rules: a component first checks its element injector tree, then the environment injector chain for the route, then root, then platform. A child environment injector can override a token from the parent for its subtree only.
Pitfalls: an injector that you create must be destroyed, or services leak. Services provided in a route are not available to components outside it. Stateful route providers are recreated when the route is left and entered again, unless the router reuses the route.
import { EnvironmentInjector, Injectable, InjectionToken, OnDestroy, createEnvironmentInjector, inject, runInInjectionContext } from '@angular/core';
import { Routes } from '@angular/router';
export const API_URL = new InjectionToken<string>('API_URL', { factory: () => '/api' });
@Injectable()
export class DraftService implements OnDestroy {
destroyed = false;
ngOnDestroy(): void {
this.destroyed = true;
}
}
export const routes: Routes = [
{
path: 'admin',
providers: [{ provide: API_URL, useValue: '/admin-api' }, DraftService],
loadChildren: () => Promise.resolve([] as Routes),
},
];
export function withTemporaryInjector(parent: EnvironmentInjector): { url: string; draft: DraftService } {
const child = createEnvironmentInjector([{ provide: API_URL, useValue: '/preview-api' }, DraftService], parent);
const result = runInInjectionContext(child, () => ({ url: inject(API_URL), draft: inject(DraftService) }));
child.destroy(); // runs ngOnDestroy of DraftService
return result;
}Angular 20.3, type-checked. A Karma test checks that a child injector overrides the token and that `destroy()` runs the service's ngOnDestroy.
Key points
- Route `providers` create an environment injector scoped to the route and its children.
- `createEnvironmentInjector` builds an injector at run time. Destroy it when finished.
- `runInInjectionContext` lets `inject()` work in a callback with a chosen injector.
- Child injectors override tokens for their subtree only.
Common mistakes
- Creating an injector and never destroying it.
- Expecting route-provided services to be available outside the route.
- Using the injector as a general service locator everywhere.
Follow-ups
- When is a route's environment injector destroyed?
- How would you give the admin area a different API URL?
- How do dialogs get their own injector?
Tips
- Use checkout state as the example for route providers.
- Mention `destroy()`.
- Mention the lookup order from element to environment injectors.
Evaluation rubric
- Explains route providers and lifetimes.
- Uses createEnvironmentInjector and runInInjectionContext correctly.
- Covers cleanup and lookup order.