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

Injectable

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

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

选项说明
providedIn?

通过与 @NgModule 或其他 InjectorType 关联,或通过指定应在以下注入器之一中提供此可注入对象,来确定将提供该对象的注入器:

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:

参见

选项

通过与 @NgModule 或其他 InjectorType 关联,或通过指定应在以下注入器之一中提供此可注入对象,来确定将提供该对象的注入器:

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:

      
      providedIn?: Type<any> | 'root' | 'platform' | 'any' | null
    
  • 'root':在大多数应用程序中是指应用程序级注入器。

    'root' : The application-level injector in most apps.

  • 'platform' :页面上所有应用程序共享的平台注入器的特殊单例。

    'platform' : A special singleton platform injector shared by all applications on the page.

  • 'any':在每个惰性加载的模块中提供一个唯一的实例,而所有急性加载的模块共享一个实例。

    'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.

使用说明

使用 @Injectable 标记一个类可确保编译器将在注入类时生成必要的元数据,以创建类的依赖项。

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