
inject() Isn't a Service Locator: Understanding the Injection Context
- كاتب موثّق
- Angular 22
محتويات المقال
/admin. Instead of being redirected to the login page, they stay where they are, and the console shows NG0203: "The Router token injection failed. inject() function must be called from an injection context". The guard does call inject(Router), and guards do run in an injection context. But that call sits on the line after an await, on a branch that an admin never reaches.
The common misconception
inject() is Angular's global way to get a service. Import it, pass it a class, and you get the instance, anywhere: in a method, a setTimeout callback, a subscribe() handler or after an await.
inject() is a plain function with no decorator and no this, so it looks like a global getter, the ServiceLocator.get() that many back-end frameworks offer. It also works in more places than constructor parameters ever did: field initializers, functional guards, resolvers and interceptors. Tests reinforce it, because TestBed.inject() really does work anywhere in a spec. That's a different API, though: a method on an object that holds an injector. The standalone inject() holds nothing.
What actually happens
inject() reads the injector that is current right now
InjectionToken factories, guards, resolvers and interceptors work the same way: Angular sets the injector, calls your function and resets it when the call returns. That window is the , and inject() only reads what's in it.
inject(CartStore) starts at that component's element injector and walks up, so two components can receive different instances of the same service. A global locator would always give the same answer; inject() answers for the context that is running.
Why methods, callbacks and await fall outside
ngOnInit runs after the instance exists, so the window is already closed; the NG0203 docs use exactly that example. A click handler, a setTimeout callback and a subscribe() callback run later too.
await is the subtle case, because the code is still inside the same function. An async function runs synchronously only up to its first await. The rest continues in a later microtask, after Angular's call has returned and the previous context is back. The runInInjectionContext() docs say it directly: inject() is usable only synchronously, never in asynchronous callbacks or after an await.
import { inject } from '@angular/core';import { CanActivateFn, Router } from '@angular/router';export const adminGuard: CanActivateFn = async () => { const session = await inject(AuthService).loadSession(); // After the await: no injection context, so NG0203 return session.isAdmin || inject(Router).parseUrl('/login');};import { inject } from '@angular/core';import { CanActivateFn, Router } from '@angular/router';export const adminGuard: CanActivateFn = async () => { // Resolve every dependency before the first await const auth = inject(AuthService); const router = inject(Router); const session = await auth.loadSession(); return session.isAdmin || router.parseUrl('/login');};inject(AuthService) works because it's evaluated before the await suspends the function. The fix is a habit, not a workaround: treat inject() calls as declarations at the top of a class or function, and use the references they return everywhere else.
Helpers that call inject() for you
inject() internally, so they follow the same rule. takeUntilDestroyed() injects a DestroyRef, toSignal() and effect() need one to clean up, and input(), output() and viewChild() belong in field initializers. In development mode they check the context first and put their own name in the error, as in "takeUntilDestroyed() can only be used within an injection context". The cleanup helpers accept what they need as an argument instead: a DestroyRef for takeUntilDestroyed(), an injector option for toSignal() and effect().
import { Component, DestroyRef, inject, input, signal } from '@angular/core';import { takeUntilDestroyed } from '@angular/core/rxjs-interop';@Component({ selector: 'app-price-ticker', template: `{{ price() }}` })export class PriceTicker { readonly symbol = input.required<string>(); readonly price = signal(0); private readonly feed = inject(PriceFeed); private readonly destroyRef = inject(DestroyRef); ngOnInit() { // Inputs are ready here, but the injection context is gone: // pass the DestroyRef that a field initializer captured. this.feed.prices(this.symbol()) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((p) => this.price.set(p)); }}ngOnInit because it needs the symbol input, which isn't set yet in the constructor. Without the argument, takeUntilDestroyed() would throw there.
useFactory or InjectionToken factory | ||
HttpClient calls it in its injector's context | ||
ngOnInit, methods, event handlers | ||
await, in setTimeout or subscribe() | ||
runInInjectionContext(injector, fn) | fn returns |
How to apply it in your project
Find inject() calls that run late Search for inject(and look at where each call sits: inside lifecycle hooks, methods,subscribe()orthen()callbacks, or below anawait. Each one fails on the first path that reaches it, which may be a rare one.Hoist them to the top Move each call to a field initializer, the constructor, or the first lines of the guard or factory, and use the reference later. Pass the context to late helpers When takeUntilDestroyed(),toSignal()oreffect()must run after construction, pass aDestroyRefor{ injector }that you injected in a field. For a lookup that truly happens later, injectInjectorand callinjector.get(), which names its injector explicitly.Test functions in a context To unit test a guard or helper that calls inject(), run it insideTestBed.runInInjectionContext(), and add a test for every branch, not only the happy path.
Key takeaways
inject()reads the injector Angular has made current while it builds a class or calls a factory, guard or interceptor; it isn't a global lookup.The context is synchronous: methods, lifecycle hooks, callbacks and everything after an awaitare outside it.Call inject()at the top and keep the references; passDestroyReforinjectorto helpers you call later.For late lookups, injector.get()names its injector;runInInjectionContext()covers synchronous code only.
التعليقات (0)