inject
Injects a token from the currently active injector.
inject is only supported in an injection context. It
can be used during:
- Construction (via the
constructor) of a class being instantiated by the DI system, such as an@Injectableor@Component. - In the initializer for fields of such classes.
- In the factory function specified for
useFactoryof aProvideror an@Injectable. - In the
factoryfunction specified for anInjectionToken. - In a stackframe of a function call in a DI context
API
function inject<T>(token: ProviderToken<T>): T;
function inject<T>(
token: ProviderToken<T>,
options: InjectOptions & { optional?: false | undefined },
): T;
function inject<T>(token: ProviderToken<T>, options: InjectOptions): T | null;
function inject(token: HostAttributeToken): string;
function inject(
token: HostAttributeToken,
options: { optional: true },
): string | null;
function inject(
token: HostAttributeToken,
options: { optional: false },
): string;function inject<T>(token: ProviderToken<T>): T;Tfunction inject<T>(token: ProviderToken<T>, options: InjectOptions & { optional?: false | undefined; }): T;Tfunction inject<T>(token: ProviderToken<T>, options: InjectOptions): T | null;T | nullfunction inject(token: HostAttributeToken): string;HostAttributeTokenA token that represents a static attribute on the host node that should be injected.
stringfunction inject(token: HostAttributeToken, options: { optional: true; }): string | null;HostAttributeTokenA token that represents a static attribute on the host node that should be injected.
{ optional: true; }string | nullfunction inject(token: HostAttributeToken, options: { optional: false; }): string;HostAttributeTokenA token that represents a static attribute on the host node that should be injected.
{ optional: false; }stringUsage Notes
In practice the inject() calls are allowed in a constructor, a constructor parameter and a
field initializer:
@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 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 context will result in error. Most
notably, calls to inject() are disallowed after a class instance was created, in methods
(including lifecycle hooks):