Angular依赖注入的学习笔记

188 阅读1分钟

Angular官方文档

Specifying a provider token

If you specify the service class as the provider token, the default behavior is for the injector to instantiate that class with new.
In the following example, the Logger class provides a Logger instance.

providers: [Logger]

NgModule的providers区域里,指定provider token. 如果将一个服务类直接指定成provider token,默认的行为就是,injector直接用new来初始化那个类。

上面的例子,会触发Logger的构造函数。等价于:

[{ provide: Logger, useClass: Logger }]

这个完整的声明在Angular官方文档里称为expanded provider configuration, 是一个包含两个属性的对象。

  • The provide property holds the token that serves as the key for both locating a dependency value and configuring the injector.

provide属性包含一个token,用于定位一个dependency value和配置injector.

  • The second property is a provider definition object, which tells the injector how to create the dependency value. The provider-definition key can be useClass, as in the example. It can also be useExisting, useValue, or useFactory. Each of these keys provides a different type of dependency, as discussed below.

第二个属性是一个provider定义对象,告诉injector如何创建dependency value. 这个定义可以是useClass,useExisting,useValue,或者useFactory.

一些例子:

[{ provide: Logger, useClass: BetterLogger }]

当使用Logger token时,injector返回BetterLogger的实例。

Aliasing class providers

To alias a class provider, specify the alias and the class provider in the providers array with the useExisting property.

In the following example, the injector injects the singleton instance of NewLogger when the component asks for either the new or the old logger. In this way, OldLogger is an alias for NewLogger.

下列的配置,会导致Component需要使用OldLogger时,会返回NewLogger的singleton实例。当然,如果请求NewLogger,亦会返回NewLogger实例。因此这种情形下,OldLogger是NewLogger语义层面的alias.

[ NewLogger,
  // Alias OldLogger w/ reference to NewLogger
  { provide: OldLogger, useExisting: NewLogger}]