当前位置:网站首页>SAP Spartacus 中的依赖注入 Dependency Injection 介绍
SAP Spartacus 中的依赖注入 Dependency Injection 介绍
2022-06-26 21:18:00 【华为云】
先了解 Angular 中的依赖注入
依赖项是指某个类执行其功能所需的服务或对象。依赖项注入(DI)是一种设计模式,在这种设计模式中,类会从外部源请求依赖项而不是让类自己来创建它们。
Angular 的 DI 框架会在实例化某个类时为其提供依赖。你可以使用 Angular DI 来提高应用程序的灵活性和模块化程度。
如何创建一个新的可以被注入的 service ?
命令行:ng generate service heroes/hero
自动生成的代码,注意注解 @Injectable:
import { Injectable } from '@angular/core';@Injectable({ providedIn: 'root',})export class HeroService { constructor() { }}@Injectable() 装饰器会指定 Angular 可以在 DI 体系中使用此类。元数据 providedIn: ‘root’ 表示 HeroService 在整个应用程序中都是可见的。
配置提供者
通过配置提供者,你可以把服务提供给那些需要它们的应用部件。
依赖提供者会使用 DI 令牌来配置注入器,注入器会用它来提供这个依赖值的具体的、运行时版本。
如果你把服务类指定为提供者令牌,那么注入器的默认行为是用 new 来实例化那个类。
在下面这个例子中,Logger 类提供了 Logger 的实例。
providers: [Logger]当使用提供者配置注入器时,会将该提供者与依赖项注入令牌(或叫 DI 令牌)关联起来。注入器允许 Angular 创建任何内部依赖项的映射。DI 令牌会充当该映射的键名。
当你使用 HeroService 类的类型来定义构造函数参数时,Angular 会注入与这个 HeroService 类令牌相关联的服务:
constructor(heroService: HeroService)这里构造函数参数 heroService 实际上是一个令牌。
这个配置:
providers: [Logger]实际上是下面写法的简写:
[{ provide: Logger, useClass: Logger }]- provide 属性存有令牌,它作为一个 key,在定位依赖值和配置注入器时使用。
- 第二个属性是一个提供者定义对象,它告诉注入器要如何创建依赖值。 提供者定义对象中的 key 可以是 useClass —— 就像这个例子中一样。 也可以是 useExisting、useValue 或 useFactory。 每一个 key 都用于提供一种不同类型的依赖。
不同的类可以提供相同的服务。例如,以下代码告诉注入器,当组件使用 Logger 令牌请求一个 logger 时,给它返回一个 BetterLogger.
这样,当我们的应用程序,在 constructor 里使用下面代码试图注入 Logger 时:
constructor(logger: Logger)运行时我们拿到的就是 BetterLogger 实例。
injection token 的使用方法
使用 TypeScript interface 定义一个 AppConfig 类型(略)
基于 AppConfig 类型创建一个常量:
export const HERO_DI_CONFIG: AppConfig = { apiEndpoint: 'api.heroes.com', title: 'Dependency Injection'};- 要提供并注入配置对象,请在 @NgModule() 的 providers 数组中指定该对象。
providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }],上面代码里 provide 属性 APP_CONFIG 就是一个令牌,我们还需要使用代码创建这个令牌。
import { InjectionToken } from '@angular/core';export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');其中AppConfig 通过类型参数传入令牌构造函数里。app.config 是令牌描述信息。
- 最后一步,在应用程序的构造函数里,用 @Inject,注入这个令牌。运行时,config 的值即为令牌关联的常量:HERO_DI_CONFIG
constructor(@Inject(APP_CONFIG) config: AppConfig) { this.title = config.title;}为什么我们不能直接把第一步用 interface 创建的 AppConfig 作为 provide 的值,而要大费周章,创建一个 InjectionToken 呢?
虽然 TypeScript 的 AppConfig 接口可以在类中提供类型支持,但它在依赖注入时却没有任何作用。在 TypeScript 中,接口是一项设计期工件,它没有可供 DI 框架使用的运行时表示形式或令牌。
当转译器把 TypeScript 转换成 JavaScript 时,接口就会消失,因为 JavaScript 没有接口。
由于 Angular 在运行期没有接口,所以该接口不能作为令牌,也不能注入它。
因此下列代码不能工作:
// Can't use interface as provider token[{ provide: AppConfig, useValue: HERO_DI_CONFIG })]看一个 SAP Spartacus 中 Injection Token 的使用例子:

export const PAGE_LAYOUT_HANDLER = new InjectionToken<PageLayoutHandler[]>( 'PageLayoutHandler');在 Cart.module.ts 里使用到了这个令牌:

最后在 PageLayoutService 里使用到了这个令牌指向的服务实例:PageLayoutHandler 组成的数组。

边栏推荐
- VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
- leetcode刷题:字符串03(剑指 Offer 05. 替换空格)
- DLA模型(分类模型+改进版分割模型) + 可变形卷积
- Mr. Sun's version of JDBC (21:34:25, June 12, 2022)
- Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
- Common concurrent testing tools and pressure testing methods
- 股票炒股注册开户有没有什么风险?安全吗?
- 这些地区考研太疯狂!哪个地区报考人数最多?
- lotus configurations
- 剑指 Offer II 098. 路径的数目 / 剑指 Offer II 099. 最小路径之和
猜你喜欢
![[serialization] how to master the core technology of opengauss database? Secret 5: master database security (6)](/img/a8/622cddae2ac8c383979ed51d36bca9.jpg)
[serialization] how to master the core technology of opengauss database? Secret 5: master database security (6)

【protobuf 】protobuf 升级后带来的一些坑

API管理之利剑 -- Eolink

Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders

The source code that everyone can understand (I) the overall architecture of ahooks

Leetcode question brushing: String 05 (Sword finger offer 58 - ii. left rotation string)

【 protobuf 】 quelques puits causés par la mise à niveau de protobuf

传纸条【动态规划】

Leetcode question brushing: String 03 (Sword finger offer 05. replace space)

Looking back at the moon
随机推荐
Jz-062- the k-th node of binary search tree
Dynamic planning 111
在哪家证券公司开户最方便最安全可靠
Looking back at the moon
【protobuf 】protobuf 昇級後帶來的一些坑
0 basic C language (1)
Leetcode question brushing: String 03 (Sword finger offer 05. replace space)
Simple Lianliankan games based on QT
QT两种方法实现定时器
手机股票注册开户有没有什么风险?安全吗?
swagger:如何生成漂亮的静态文档说明页
The postgraduate entrance examination in these areas is crazy! Which area has the largest number of candidates?
0基础学c语言(3)
The importance of using fonts correctly in DataWindow
基于启发式搜索的一字棋
分布式ID生成系统
Muke 8. Service fault tolerance Sentinel
不要做巨婴了
windows系統下怎麼安裝mysql8.0數據庫?(圖文教程)
DAST 黑盒漏洞扫描器 第五篇:漏洞扫描引擎与服务能力