Sub topic 13
Injection Context Rules and runInInjectionContext
This chapter assumes you know how to call inject() and how providers are registered. It also uses the CartService and APP_CONFIG token from earlier chapters. The aim is to know where inject() is allowed and what to do when you need a dependency somewhere it isn't.
What an injection context is
inject() takes no injector argument. It reads the "current injector," which Angular sets only while it is creating something or running code on your behalf. The window during which a current injector exists is called the injection context. If you call inject() outside it, Angular throws error NG0203: "inject() must be called from an injection context."
Where inject() works
| Location | Injection context? |
|---|---|
| Class field initializers of a component, directive, pipe, or service | Yes |
| Constructor body | Yes |
| `useFactory` functions in providers | Yes |
| Functional route guards, resolvers, and `HttpInterceptorFn` | Yes |
| Callback passed to `runInInjectionContext` | Yes |
| `ngOnInit` and other lifecycle hooks | No |
| Event handlers, `setTimeout`, `subscribe` callbacks, `async` code after `await` | No |
The await row catches many people. Code before the first await in a constructor runs synchronously, so it is still in context. Code after the await resumes later, when Angular has already cleared the current injector.
The common mistake
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-broken',
standalone: true,
template: `{{ total }}`
})
export class BrokenComponent implements OnInit {
total = 0;
ngOnInit(): void {
const cart = inject(CartService); // NG0203 at runtime
this.total = cart.count();
}
}The fix is usually to move the call into a field initializer: private readonly cart = inject(CartService);. Do this whenever you can.
runInInjectionContext
Sometimes you only know at runtime that you need a dependency, for example inside a click handler or after a lazy import(). In that case, capture an Injector while you are still in context. Later, call runInInjectionContext to make that injector current for the length of a callback.
import { Component, Injector, inject, runInInjectionContext } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-lazy-cart',
standalone: true,
template: `<button (click)="load()">Load</button> {{ total }}`
})
export class LazyCartComponent {
private readonly injector = inject(Injector);
total = 0;
load(): void {
const cart = runInInjectionContext(this.injector, () => inject(CartService));
this.total = cart.count();
}
}runInInjectionContext returns whatever the callback returns. Resolution starts from the injector you pass in. Passing a component's Injector therefore sees that component's element providers, while passing an EnvironmentInjector sees only environment providers.
Writing inject-based helper functions
Reusable injectX() helpers only work when someone calls them in context. Use assertInInjectionContext so a misplaced call fails with an error that names your helper.
import { assertInInjectionContext, inject } from '@angular/core';
import { APP_CONFIG } from './app.config';
export function injectApiUrl(): string {
assertInInjectionContext(injectApiUrl);
return inject(APP_CONFIG).apiUrl;
}Angular APIs built on inject() follow the same rule. toSignal(), effect(), and takeUntilDestroyed() need an injection context unless you pass them an injector option or, for takeUntilDestroyed(), a DestroyRef.
Exercise
A service constructor runs const data = await fetchSettings(); and then const logger = inject(Logger);. Why does this throw NG0203, and what are two ways to fix it?
Show answer
The code after await resumes asynchronously, after Angular has cleared the current injector, so the second inject() runs outside the injection context. Fix 1: call inject(Logger) before the await, or move it to a field initializer. Fix 2: capture inject(Injector) before the await and then call runInInjectionContext(injector, () => inject(Logger)).
Exercise
You call runInInjectionContext with an EnvironmentInjector and request a service that is listed only in a component's providers array. What happens?
Show answer
Resolution fails, so Angular throws a "No provider" error, or returns null if you pass { optional: true }. An EnvironmentInjector cannot see element injectors, so you need to pass the component's own Injector instead.