الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

inject() Isn't a Service Locator: Understanding the Injection Context

inject() reads the injector Angular sets for a moment. In a method, a callback or after an await, there's none.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

An admin guard passes code review and every demo, because the demo account is an admin. Then the first regular user opens /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

The belief: 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.

It's an easy model to adopt. 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

The system tracks one current injector. When Angular creates a component, it makes that component's injector current, runs the constructor and the field initializers, then restores whatever was current before. Provider factories, 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.

That's also why the result depends on where you call it. In a component, 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

The window is synchronous. It stays open while Angular's call into your constructor or factory is on the stack, and it closes when that call returns. A like 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.

TypeScript admin.guard.ts
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');};

The first 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

Several Angular APIs call 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().

TypeScript price-ticker.ts
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));  }}

The subscription has to start in ngOnInit because it needs the symbol input, which isn't set yet in the constructor. Without the argument, takeUntilDestroyed() would throw there.

Where the call runsInjection context?Why
Constructor or field initializerYesAngular is creating the instance
useFactory or InjectionToken factoryYesAngular calls it while resolving the token
Functional guard, resolver or interceptorYesThe router or HttpClient calls it in its injector's context
ngOnInit, methods, event handlersNoThe instance already exists
After an await, in setTimeout or subscribe()NoIt runs after Angular's call returned
Inside runInInjectionContext(injector, fn)Until fn returnsYou set the current injector yourself

How to apply it in your project

  1. Find inject() calls that run lateSearch for inject( and look at where each call sits: inside lifecycle hooks, methods, subscribe() or then() callbacks, or below an await. Each one fails on the first path that reaches it, which may be a rare one.
  2. Hoist them to the topMove each call to a field initializer, the constructor, or the first lines of the guard or factory, and use the reference later.
  3. Pass the context to late helpersWhen takeUntilDestroyed(), toSignal() or effect() must run after construction, pass a DestroyRef or { injector } that you injected in a field. For a lookup that truly happens later, inject Injector and call injector.get(), which names its injector explicitly.
  4. Test functions in a contextTo unit test a guard or helper that calls inject(), run it inside TestBed.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 await are outside it.
  • Call inject() at the top and keep the references; pass DestroyRef or injector to helpers you call later.
  • For late lookups, injector.get() names its injector; runInInjectionContext() covers synchronous code only.

📚 المصادر

  1. Injection context — Angular
  2. NG0203: inject() must be called from an injection context — Angular
  3. runInInjectionContext — Angular API
  4. takeUntilDestroyed — Angular API

التعليقات (0)