← Back to Angular, page 7

angular-0140 · Hard senior

How do route-level providers and environment injectors work, and how do you create an injector at run time for isolated state?

A route's providers array creates an environment injector for that route and its children, so services live as long as the route and are separate from the root. You can also build an injector at run time with createEnvironmentInjector, and use runInInjectionContext to call functions that use inject() with it.

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 to createComponent(Component, { environmentInjector }) or to ViewContainerRef.createComponent. Destroy it with injector.destroy() when done, which runs ngOnDestroy of its services.
  • runInInjectionContext(injector, () => inject(Service)) runs a function with an injector active, so functions that call inject() can be used outside constructors, for example in a callback or a test.
  • EnvironmentInjector itself can be injected, and inject(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.

typescript
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.