Angular throws NG0203 because inject() runs outside an injection context
NG0203: inject() must be called from an injection contextShort answer
NG0203 means inject() ran at a moment when Angular was not creating anything. It only works in a constructor, a field initializer, a provider or token factory, or a function called from one of those. Move the call to a field or constructor, wrap it in runInInjectionContext, or in tests use TestBed.runInInjectionContext.
Fix it fast
1Find out which cause you have
Read the stack trace from the top and find the first line in your own code. That line is the inject() call (or a function that calls it), and where it sits decides the cause.
ng serve # then open the browser console and read the NG0203 stack trace2Match what you see, then jump to its fix
- 1
The stack trace points to ngOnInit, an event handler, a subscribe callback or another method of the classinject() is called inside a method or a lifecycle hookFix - 2
The stack trace shows your own function (for example a utility or a function used in a callback) that calls inject(), called from a timer, a promise or a plain methodA helper function that calls inject() is run from outside any injection contextFix - 3
NG0203 appears only in the spec, from a function or factory you call by handA unit test calls code that uses inject() directlyFix
- 1
What does the error look like?
NG0203: inject() must be called from an injection context
Cause 1 of 3
inject() is called inside a method or a lifecycle hook
1Check
Angular's NG0203 page lists the places where inject() is allowed: constructors, constructor parameters, field initializers and provider factories. A method runs after the instance exists, which the page calls too late.
grep -rn "inject(" src/app | grep -v "= inject("2Fix
Call inject() once in a field initializer and use the stored value inside methods.
export class ProfileComponent {
private http = inject(HttpClient);
ngOnInit() {
this.http.get('/api/me').subscribe();
}
}3Verify
Reload the page and confirm the console no longer shows NG0203.
ng buildConfirmed by angular.dev
Cause 2 of 3
A helper function that calls inject() is run from outside any injection context
1Check
The Angular dependency-injection context guide says inject() works in a stack frame that runs within an injection context, such as a router guard. A helper called later, from a method, has no such context.
grep -rn "function .*inject\|runInInjectionContext" src/app2Fix
Inject an EnvironmentInjector (or Injector) in a field initializer, and run the helper through runInInjectionContext. As an alternative, move the inject() call into the field initializer and pass the result in as an argument.
import { EnvironmentInjector, inject, runInInjectionContext } from '@angular/core';
export class ReportService {
private injector = inject(EnvironmentInjector);
run() {
runInInjectionContext(this.injector, () => {
inject(SomeService);
});
}
}3Verify
Trigger the code path that failed and confirm no NG0203 is thrown.
ng testConfirmed by angular.dev
Cause 3 of 3
A unit test calls code that uses inject() directly
1Check
Outside Angular's own creation of a class, a test has no injection context. The NG0203 page names TestBed.runInInjectionContext as the way to supply one.
grep -rn "inject(" src --include=*.spec.ts2Fix
Run the call inside TestBed.runInInjectionContext, after configuring the testing module.
it('reads the service', () => {
const result = TestBed.runInInjectionContext(() => myInjectingFunction());
expect(result).toBeDefined();
});3Verify
Run the spec again.
ng testConfirmed by angular.dev
How do I stop it coming back?
- Declare dependencies as fields (private http = inject(HttpClient)) so they are created at construction time.
- In helper functions that use inject(), call assertInInjectionContext(theFunction) first, so a wrong call gives an error that names your helper.
- Keep inject() out of callbacks; read the dependency into a variable before the callback starts.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Related fixes
Back end
Airflow SSHOperator stops a long script with SSH command timed out
airflow.exceptions.AirflowException: SSH command timed out
SSHOperator waits only 10 seconds for a command by default.
3 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
ng serve says it cannot determine the project or target
Cannot determine project for command.
The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.
3 causes, each with a fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
ng serve cannot find the dev-server builder package
Could not find the implementation for builder @angular/build:dev-server
The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.
3 causes, each with a fix