GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Docs
  • Tutorials
  • Playground
  • Reference

This view

  • Original page
  • New address

GeezerVison is showing angular.dev — NG0203: `inject()` must be called from an injection context • Angular

You see this error when you try to use the inject function outside of the allowed injection context. The injection context is available during the class creation and initialization. It is also available to functions used with runInInjectionContext.

In practice the inject() calls are allowed in a constructor, a constructor parameter and a field initializer:

@Service()
export class Car {
  radio: Radio | undefined;

  // OK: field initializer
  spareTyre = inject(Tyre);

  constructor() {
    // OK: constructor body
    this.radio = inject(Radio);
  }
}

It is also legal to call inject from a provider's factory:

providers: [
  {
    provide: Car,
    useFactory: () => {
      // OK: a class factory
      const engine = inject(Engine);
      return new Car(engine);
    },
  },
];

Calls to the inject function outside of the class creation or runInInjectionContext will result in error. Most notably, calls to inject() are disallowed after a class instance was created, in methods (including lifecycle hooks):

@Component({ ... })
export class Car {
  ngOnInit() {
    // ERROR: too late, the component instance was already created
    const engine = inject(Engine);
    engine.start();
  }
}

Debugging the error

Work backwards from the stack trace of the error to identify a place where the disallowed call to inject() is located.

To fix the error move the inject call to an allowed place (usually a class constructor or a field initializer).

NOTE: If you are running in a test context, TestBed.runInInjectionContext will enable inject() to succeed.

TestBed.runInInjectionContext(() => {
  // ...
});
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.