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

Injectable

标记性元数据,表示一个类可以由 Injector 进行创建。

Marks a class as available to Injector for creation.

选项说明
providedIn

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in the 'root' injector, which will be the application-level injector in most apps.

参见

选项

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in the 'root' injector, which will be the application-level injector in most apps.

providedIn: Type<any> | 'root' | null
      
      providedIn: Type<any> | 'root' | null
    

使用说明

下面的例子展示了如何正确的把服务类标记为可注入的(Injectable)。

The following example shows how service classes are properly marked as injectable.

@Injectable() class UsefulService { } @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = Injector.create({ providers: [ {provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []} ] }); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
      
      
  1. @Injectable()
  2. class UsefulService {
  3. }
  4.  
  5. @Injectable()
  6. class NeedsService {
  7. constructor(public service: UsefulService) {}
  8. }
  9.  
  10. const injector = Injector.create({
  11. providers: [
  12. {provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}
  13. ]
  14. });
  15. expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);