填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

inject

从当前活动的注入器中注入令牌。

Injects a token from the currently active injector.

查看"说明"...

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

说明

必须在工厂函数的上下文中使用,比如为 InjectionToken 定义的函数。如果未从这样的上下文中调用,则会引发错误。

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.

在这样的工厂函数中,使用此函数来请求注入依赖项比提供额外的依赖项数组(在 useFactory 提供者中这很常见)要更快且类型安全性更高。

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).

Further information available in the 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();