October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Angular Injection Context: Where `inject()` Works and How to Fix NG0203

Angular’s injection context is synchronous: use inject() during DI-managed construction or supported factories, and capture dependencies for later methods and async callbacks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An Angular injection context is a synchronous execution frame in which Angular makes an injector available to inject(). It is available during DI-managed construction, including field initializers, and in certain factories and Angular-run functional APIs. It does not automatically extend to later methods, lifecycle hooks, or asynchronous callbacks.

What is an injection context in Angular?

An injection context is where Angular has made a current injector available to the code running at that moment. Calling inject(Token) in that frame asks the injector to resolve the token. This is about where and when the code executes, not simply whether it belongs to a class that uses dependency injection.

As an Amazon Associate I earn from qualifying purchases.

Angular documents these common valid contexts:

  • A constructor of a class instantiated by Angular’s dependency-injection system.
  • A field initializer of a class instantiated by that system.
  • A provider or injectable factory configured with useFactory.
  • An InjectionToken factory.
  • A synchronous stack frame called while an injection context is already active, including Angular-executed functional APIs such as route guards.

See Angular’s injection context guide and inject() API reference for the documented contexts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does inject() fail in ngOnInit or a method?

Angular runs a DI-managed class’s constructor and field initializers while establishing its dependencies. An ordinary method such as onClick() runs later, and lifecycle hooks such as ngOnInit run after construction. Neither becomes an injection context just because it belongs to an injected component or service.

import { Component, inject } from '@angular/core';
import { DataService } from './data.service';

@Component({ selector: 'app-example', template: '' })
export class ExampleComponent {
  private readonly dataService = inject(DataService); // valid field initializer

  ngOnInit() {
    // inject(DataService); // NG0203: this runs after construction
    this.dataService.load();
  }
}

Angular reports the invalid call as NG0203: inject() must be called from an injection context. Its NG0203 error reference advises checking where the failing call occurs; the DI troubleshooting guide covers ways to handle later lookups.

Can I use inject() after await?

No. The injection context is synchronous. It is not carried into a promise continuation, timer, event callback, or code after await. runInInjectionContext also makes the injector current only while its callback’s synchronous stack frame runs; it cannot preserve the context for asynchronous work started inside that callback. Angular explains this boundary in its runInInjectionContext API reference.

runInInjectionContext(injector, () => {
  const service = inject(DataService); // valid here
  setTimeout(() => {
    // inject(DataService) is not valid here
    service.load(); // use the captured reference instead
  });
});

How to fix NG0203

Capture the dependency during construction

For component, directive, or service code that needs a dependency later, inject it in a constructor or field initializer and retain the reference. Use that reference from methods, lifecycle hooks, and callbacks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an existing injector for a later lookup

If you need a one-off lookup in later code and already have an Injector, use Injector.get(Token). This performs retrieval through that injector without requiring the later method itself to be an injection context.

Wrap a synchronous callback when it must call inject()

When an external synchronous callback specifically needs to invoke inject(), call it through runInInjectionContext(injector, callback), using an injector you already have. Any dependency needed by asynchronous work must still be captured before the callback returns.

In tests, use TestBed’s context helper

Angular’s NG0203 documentation identifies TestBed.runInInjectionContext for test code that must call inject() in a context supplied by TestBed. See the error reference for details.

An injection context does not guarantee a provider exists

Context and resolution are separate questions. A current injector makes inject() eligible to run, but that injector must still be able to resolve the requested token. If the error is NG0203, investigate where the call runs. If a context is active but a token cannot be resolved, investigate provider registration and scope instead. Angular describes the EnvironmentInjector and ElementInjector hierarchies and how provider configuration affects resolution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make reusable helpers fail more clearly

A helper that calls inject() can use assertInInjectionContext(helperFunction) to check its precondition and produce a more useful error associated with that helper. The assertion does not create an injection context; callers must still invoke the helper from a valid one. Angular documents this in its injection context guide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.