W3cubDocs

/Angular

inject

const

Injects a token from the currently active injector.

See more...

const inject: { <T>(token: Type<T> | InjectionToken<T>): T; <T>(token: Type<T> | InjectionToken<T>, flags?: InjectFlags): T; };

Description

Must be used in the context of a factory function such as one defined for an InjectionToken. Throws an error if not called from such a context.

Within such a factory function, using this function to request injection of a dependency is faster and more type-safe than providing an additional array of dependencies (as has been common with useFactory providers).

Usage notes

Example

class MyService {
  constructor(readonly myDep: MyDep) {}
}

const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
  providedIn: 'root',
  factory: () => new MyService(inject(MyDep)),
});

const instance = injector.get(MY_SERVICE_TOKEN);
expect(instance instanceof MyService).toBeTruthy();
expect(instance.myDep instanceof MyDep).toBeTruthy();

© 2010–2019 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/core/inject