StackOverflow上的一个帖子.

从上图能看出,所有注入的示例都通过factory方法返回,只是factory方法的实现有所差异。

As we can see in the picture above all of providers can be presented similar useFactory. When it’s the time to get an instance of provider angular just calls factory function.

一些例子:

{provide: Class1, useClass: Class1}

等价于:

Class1

而:

{provide: Class1, useClass: Class3}

you can configure, that when a constructor requests Class1 Angular DI creates an instance of Class3 and passes it to the constructor.

当构造函数的参数需要传入Class1时,Angular DI传入一个Class3的框实例到构造函数里。

而下面这个例子:

{provide: Class2, useExisting: Class2}

doesn’t result in an instance being created, but you can see this rather than an alias. If a constructor requests Class2, Angular DI looks for another provider for key Class2 and injects the instance from this Class2 provider. You can see useExisting like a reference to another provider or an alias.

当构造函数需要Class2时,Angular DI从另一个key为Class2的provider里查找,取出对应的实例进行注入。

Injectable and Provider are 2 different things. The injectable is a class DI can create an instance of, or a provided value that might be passed to a constructor. A provider is an entry in a registry of providers that DI maintains and that allows to lookup up providers by key (key is the type of a constructor parameter, a string or an InjectToken). The provider also holds information about how to “create” the injectable value/instance. DI looks up a provider, the provider provides the value, and DI passes the value (instance of an injectable or a value provided as-is) to a constructor.

Injectable和Provider是两个不同的概念。Injectable是一个class,Angular DI可以基于该class创建实例,或者DI可以提供一个值,能够传递到constructor里。DI内部维护了一个provider注册表,该注册表支持根据key查询provider.

Key is the type of a constructor parameter, a string or an InjectToken)

key是构造函数的参数,一个字符串或者InjectToken. Provider有足够的knowledge知道如何去创建一个value或者实例。

DI询问provider,provider提供值,DI将值传递到构造函数里。

If you register MyClass as provider, this is the short form of { provide: MyClass, useClass: MyValue } where provide: MyClass is the key a provider can be found with, and useClass: MyValue is a strategy passed to the provider that informs the provider what value it should provide for this key.

provide: MyClass是provider的key,Angular DI注册表里根据这个key找到provider.

useClass: MyValue, 一个传递给provider的strategy,告诉provider对于指定的key,应该提供何种value.

  • useClass: MyValue相当于"use new MyClass(…)"

  • useExisting: Foo

DI需要去查找key为Foo的provider,然后注入Foo provider提供的value.

看一些具体的例子。

UseExisting

在注入ServiceOldS时,使用ServiceNewS这个provider提供的值。

因此,运行时,old和newService两个实例指向的都是newService实例,都是ServiceNewS这个provider注入的实例:

所以最后UI上显示:

useClass

ServiceOldS被注入的是new ServiceNewS,

且和newService的实例不同,所以最后显示new service.

[{ provide: Logger, useClass: Logger }]
  • The provide property holds the token that serves as the key for both locating a dependency value and configuring the injector.

别名提供者:useExisting

useExisting 提供了一个键,让你可以把一个令牌映射成另一个令牌。实际上,第一个令牌就是第二个令牌所关联的服务的别名,这样就创建了访问同一个服务对象的两种途径。

{ provide: MinimalLogger, useExisting: LoggerService }

useExisting 的作用

你可以使用别名接口来窄化 API。下面的例子中使用别名就是为了这个目的。

想象 LoggerService 有个很大的 API 接口,远超过现有的三个方法和一个属性。你可能希望把 API 接口收窄到只有两个你确实需要的成员。在这个例子中,MinimalLogger类-接口,就这个 API 成功缩小到了只有两个成员:

// Class used as a "narrowing" interface that exposes a minimal logger
// Other members of the actual implementation are invisible
export abstract class MinimalLogger {abstract logs: string[];abstract logInfo: (msg: string) => void;
}

消费代码:

@Component({selector: 'app-hero-of-the-month',templateUrl: './hero-of-the-month.component.html',// TODO: move this aliasing, `useExisting` provider to the AppModuleproviders: [{ provide: MinimalLogger, useExisting: LoggerService }]
})
export class HeroOfTheMonthComponent {logs: string[] = [];constructor(logger: MinimalLogger) {logger.logInfo('starting up');}
}

HeroOfTheMonthComponent 构造函数的 logger 参数是一个 MinimalLogger 类型,在支持 TypeScript 感知的编辑器里,只能看到它的两个成员 logs 和 logInfo:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

Angular 依赖注入框架里 useExisting 和 useClass 的使用场景相关推荐

  1. 测试:abstract class不允许出现在Angular依赖注入框架的providers区域内

    测试用的service类: import { Injectable } from '@angular/core';@Injectable({providedIn: 'root',}) export a ...

  2. Angular 依赖注入的学习笔记

    Angular官方文档 Specifying a provider token If you specify the service class as the provider token, the ...

  3. angular依赖注入_Angular依赖注入简介

    angular依赖注入 by Neeraj Dana 由Neeraj Dana In this article, we will see how the dependency injection of ...

  4. Angular 依赖注入学习笔记之工厂函数的用法

    网址:https://angular.institute/di We can transfer any data through our apps, transform it and replace ...

  5. 给微软的依赖注入框架写一些扩展方法

    给微软的依赖注入框架写一些扩展方法 Intro 现在在项目里大多都是直接使用微软的依赖注入框架,而微软的注入方式比较简单,不如 AutoFac 使用起来灵活,于是想给微软的依赖注入增加一些扩展,使得可 ...

  6. Google Guice 一个轻量级的依赖注入框架

    1.美图 2.概述 2.1 背景 在做项目的时候,看见有段代码直接是使用Google Guice 注入了avaitor表达式. 2.1 官网 Github 主页:https://github.com/ ...

  7. 简述依赖注入框架 Hilt 的实现原理

    目录 结论 1.Application 注解 @HiltAndroidApp 注解生成的文件 代码的执行流程 2.对象的创建流程 build 一下,看一下生成的类: 对象初始化流程 ActivityC ...

  8. Android 依赖注入框架 Dagger2使用

    前言 Dagger 2这个匕首确实很难上手,上手后又比较难瞬间掌握,可以这么说,刚开始使用就是用来尝(zhuang)鲜(X)的,但相信随着使用的加深,会不断体会到它对于整个项目架构的极强辅助作用,能使 ...

  9. Android神匕首—Dagger2依赖注入框架详解

    简介 Dagger-匕首,鼎鼎大名的Square公司旗下又一把利刃(没错!还有一把黄油刀,唤作ButterKnife) Dagger2 是一个Android依赖注入框架,由谷歌开发,最早的版本Dagg ...

  10. android dagger2 懒加载,Android Dagger依赖注入框架浅析

    今天接触了Dagger这套android的依赖注入框架(DI框架),感觉跟Spring 的IOC差不多吧.这个框架它的好处是它没有采用反射技术(Spring是用反射的),而是用预编译技术,因为基于反射 ...

最新文章

  1. 极验行为验证的使用方法
  2. POJ 1321 棋盘问题 题解
  3. static关键字(修饰函数、局部变量、全局变量)
  4. cmd执行python 环境变量应该怎么写_python怎么运行py文件?.py文件cmd命令方法及环境变量配置教程...
  5. 中微公司2020年净利4.92亿元 投资中芯国际赚2.62亿
  6. 旷视科技印奇:孜孜不倦做硬件 看好3个应用场景
  7. 不会装系统?有这篇就够了!
  8. python3入门经典100例-ZH奶酪:编程语言入门经典100例【Python版】
  9. 利用NMDS对药物处理下肠道菌群微生物群落多态性分析
  10. 计算机代表学校拿什么奖,学校荣获第十届中国大学生计算机设计大赛优秀组织奖...
  11. 转载(中文、日文、韩文编码问题)
  12. FORTIFY_SOURCE详解
  13. TCL/TK脚本应用tclkit工具打包
  14. IntelliJ IDEA如何整理代码格式
  15. [笔记]Windows核心编程《二十》DLL的高级操作技术
  16. 一个又离不开的软件:图形化远程控制APP向日葵
  17. RSA - 非对称加密算法简要介绍与JAVA实现
  18. 《托尔斯泰的烦恼》纪录片笔记
  19. 2020南京理工大学计算机考研经验
  20. 大企业的计算机设备维护,企业计算机系统维护措施

热门文章

  1. unity Google 广告接入 SDK Android
  2. eclipse启动报错,显示找不到指定路径的JRE
  3. 按键精灵定义全局变量_按键精灵全局环境变量
  4. 沉没的王国---揭秘滇东自杞国(5)
  5. NavigationDuplicated: Avoided redundant navigation to current location
  6. 1)华为手机使用电脑批量管理联系人 - 2)华为云空间联系人同步到手机 - 3)华为手机导入联系人列表
  7. 十分钟了结MySQL information_schema
  8. word转换成pdf后图片压缩失真的解决方法
  9. java 提示语法错误_java常见语法错误
  10. 【MFC】解决窗口大小改变之后,ComboBox当前选项文字出现蓝色背景