关于angular:Angular-为什么要引入-injection-token-的概念

1次阅读

共计 1123 个字符,预计需要花费 3 分钟才能阅读完成。

你能够定义和应用一个 InjectionToken 对象来为 非类 的依赖抉择一个提供者令牌。

这里的重点是:非类。

下列例子定义了一个类型为 InjectionToken 的 APP_CONFIG .

import {InjectionToken} from '@angular/core';

export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');

这里的 APP_CONFIG 只是一个令牌 token,或者说是一个 place holder.

可选的参数 <AppConfig> 和令牌形容 app.config 指明了此令牌的用处。
接着,用 APP_CONFIG 这个 InjectionToken 对象在组件中注册依赖提供者。

providers: [{provide: APP_CONFIG, useValue: HERO_DI_CONFIG}]

语义是,消费者代码里,注入 APP_CONFIG 的令牌,则运行时,令牌会被理论的值 HERO_DI_CONFIG 取代。这个 HERO_DI_CONFIG 不是一个 Angular class, 所以只能以 injection token 的形式注册提供者。

当初,借助参数装璜器 @Inject(),你能够把这个配置对象注入到构造函数中。

constructor(@Inject(APP_CONFIG) config: AppConfig) {this.title = config.title;}

接口和依赖注入

尽管 TypeScript 的 AppConfig 接口能够在类中提供类型反对,但它在依赖注入时却没有任何作用。在 TypeScript 中,接口是一项设计期工件,它没有可供 DI 框架应用的运行时示意模式或令牌。

当转译器把 TypeScript 转换成 JavaScript 时,接口就会隐没,因为 JavaScript 没有接口。

因为 Angular 在运行期没有接口,所以该接口不能作为令牌,也不能注入它。

因而,下列的代码是不非法的:

// Can't use interface as provider token
[{provide: AppConfig, useValue: HERO_DI_CONFIG})]

咱们不能把 interface 自身作为一个令牌,因而 Angular 引入了 injection token 的概念。

同样,下列的代码亦不非法,因为 interface 不能作为构造函数的输出参数类型注入。因而咱们须要 @Inject, 将 interface 包裹一层之后再传入构造函数。

// Can't inject using the interface as the parameter type
constructor(private config: AppConfig){}
正文完
 0