mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
Injection context has gain public visibility with the exposure of `inject`. Lets provide some insights. Closes #49774 PR Close #49782
71 lines
2.1 KiB
Markdown
71 lines
2.1 KiB
Markdown
@name `inject()` must be called from an injection context
|
|
@category runtime
|
|
@shortDescription `inject()` must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`.
|
|
|
|
@description
|
|
You see this error when you try to use the [`inject`](api/core/inject) function outside of the allowed [injection context](guide/dependency-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:
|
|
|
|
```typescript
|
|
@Injectable({providedIn: 'root'})
|
|
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`](api/core/inject) from a provider's factory:
|
|
|
|
```typescript
|
|
providers: [
|
|
{provide: Car, useFactory: () => {
|
|
// OK: a class factory
|
|
const engine = inject(Engine);
|
|
return new Car(engine);
|
|
}}
|
|
]
|
|
```
|
|
|
|
Calls to the [`inject`](api/core/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):
|
|
|
|
```typescript
|
|
@Component({ ... })
|
|
export class CarComponent {
|
|
ngOnInit() {
|
|
// ERROR: too late, the component instance was already created
|
|
const engine = inject(Engine);
|
|
engine.start();
|
|
}
|
|
}
|
|
```
|
|
|
|
@debugging
|
|
|
|
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`](api/core/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.
|
|
|
|
```typescript
|
|
TestBed.runInInjectionContext(() => {
|
|
// ...
|
|
});
|
|
```
|
|
|
|
<!-- links -->
|
|
|
|
<!-- external links -->
|
|
|
|
<!-- end links -->
|
|
|
|
@reviewed 2023-04-11
|