inject
Injects a token from the currently active injector.
const inject: { <T>(token: Type<T> | InjectionToken<T>): T; <T>(token: Type<T> | InjectionToken<T>, flags?: InjectFlags): T; };
说明
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).
使用说明
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();