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

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; };
      
      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();
      
      
  1. class MyService {
  2. constructor(readonly myDep: MyDep) {}
  3. }
  4.  
  5. const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
  6. providedIn: 'root',
  7. factory: () => new MyService(inject(MyDep)),
  8. });
  9.  
  10. const instance = injector.get(MY_SERVICE_TOKEN);
  11. expect(instance instanceof MyService).toBeTruthy();
  12. expect(instance.myDep instanceof MyDep).toBeTruthy();