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

Injectable

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

Decorator that marks a class as available to be provided and injected as a dependency.

选项说明
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 one of the following injectors:

  • 'root' : The application-level injector in most apps.
  • 'platform' : A special singleton platform injector shared by all applications on the page.
  • 'any' : The NgModule injector that receives the resolution.

参见

选项

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 one of the following injectors:

  • 'root' : The application-level injector in most apps.
  • 'platform' : A special singleton platform injector shared by all applications on the page.
  • 'any' : The NgModule injector that receives the resolution.
providedIn: Type<any> | 'root' | 'platform' | 'any' | null
      
      providedIn: Type<any> | 'root' | 'platform' | 'any' | null
    

使用说明

Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected.

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

The following example shows how a service class is properly marked so that a supporting service can be injected upon creation.

@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);
      
      @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);