网址:https://angular.institute/di

We can transfer any data through our apps, transform it and replace it.

我们能传递任何数据到我们的应用里,改变其形态,并且替换。

Another case: document and fetch can work in your browser correctly. But one day you need to build your app in SSR or precompile with nodejs. Global entities might be missing or be different in that environment.

document 和 fetch 能在浏览器环境下运行。但是如果在 SSR 下 build 应用,或者用 nodejs precompile,那么这些对象在新的环境下不再可用。

Dependency Injection mechanism manages dependencies in your application. For you as an Angular developer, it is a straightforward instrument. There are two operations: you can provide something into your DI tree or take something from it.

依赖注入机制管理应用的依赖。对于 Angular 开发者来说,有两种操作:

  1. 提供数据到依赖注入树中
  2. 从依赖注入树中获取数据

The magic is the order in which you provide and take your dependencies.
Angular creates a class instance when you ask for this the first time.

当我们试图在 DI 树里第一次获取实例时,Angular 负责实例化。

Providing value is normally used with InjectionToken. This object is like a key for DI mechanism.

我们也可以用依赖注入提供常量,通常借助 InjectionToken. 这个令牌类似依赖注入机制中的 key.

You say “I want to get this data with this key” and ask DI in a component “Do you have something for this key?”

我们使用 InjectionToken 作为 key,询问 Angular 依赖注入机制,“你维护的资源里,有针对这个 key 的值吗?”

看个具体的例子。

export const API_URL = new InjectionToken<string>('The URL of API');

在 api-url.token.ts 里,我们从 @angular/core 里导入了标准的 InjectionToken 构造器,其类型为 string,描述信息为:The URL of API.

在 app.module.ts 里,导入这个 API_URL token,然后在 module 的 NgModule 注解里,使用 useValue 提供 token key 代表的具体值:

如何使用这个 token 呢?参考下图代码:

export class AppComponent  {constructor(@Inject(API_URL) readonly apiUrl: string) {/*** Here we asked for something with a key API_URL.* There is our string in DI and we get it*/console.log(apiUrl);}
}

语义就是,在 app Component 里,使用 @Inject 注解,向 DI 树里查询,是否存在 key 为 API_URL 的注入值。

  • We can replace token value at any level of DI tree without any changes in a component - 我们可以在 DI 树上的任意层次结构里,替换 token 的值,而不需要修改 Component

  • We can mock a token value providing suitable data in tests - 在测试代码里,我们可以 mock 一个 token 值

  • The component class is fully isolated and can be used without any context

Providing a factory

这是 Angular 依赖注入的高级用法之一。

You can provide some value combining and transforming data from other tokens.

我们可以在 factory 代码里编写一些业务逻辑,执行一些数据结构变换的操作。

看个例子:

定义一个函数:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";import { AppComponent } from "./app.component";
import { PRESSED_KEY } from "./tokens/pressed-key";
import { Observable, fromEvent } from "rxjs";
import { map } from "rxjs/operators";
import { DOCUMENT } from "@angular/common";/*** It is a token value factory.** The factory is called when app.component.ts asks for* the token PRESSED_KEY the first time*/
function pressedKeyFactory(documentRef: Document): Observable<string> {return fromEvent(documentRef.body, "keydown").pipe(map((event: KeyboardEvent) => event.key));
}

构造一个 Observable 对象,当键盘被按下时,从 KeyboardEvent 里解析出具体哪一个键被按下,然后将 key 值通过 Observable 对象返回。

这个函数被当成一个工厂函数,本身接收类型为 Document 的参数,这个参数就是其依赖。

我们通过下列的语法,将名为 PRESSED_KEY 的令牌,和该工厂函数绑定在一起。

@NgModule({imports: [BrowserModule, FormsModule],declarations: [AppComponent],bootstrap: [AppComponent],providers: [{provide: PRESSED_KEY,/*** Here you can provide any token and its value will be injected* as a factory function argument*/deps: [DOCUMENT],useFactory: pressedKeyFactory}]
})

该 token 的消费方式:

更多Jerry的原创文章,尽在:“汪子熙”:

Angular 依赖注入学习笔记之工厂函数的用法相关推荐

  1. Flutter学习笔记:identical函数的用法以及常量构造函数的特点

    identical函数 用法: bool identical( Object? a, Object? b ) 作用:检查两个引用是否指向同一个对象,简单说就是检查两个实例是否共用一个存储空间 例1: ...

  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官网学习笔记

    Angular官网学习笔记 一.Angular概述 **什么是Angular:**一个基于TypeScript构建的开发平台包括: 一个基于组件的框架,用于构建可伸缩的Web应用 一组完美集成的库,涵 ...

  5. 探针一号的SQL注入学习笔记

    SQL注入学习笔记 文章目录 SQL注入学习笔记 1.问题 2.sqlilabs环境配置 3.第一个注入过程详解(整型注入) 4.跨库注入 5.字符型注入 5.报错注入 6.POST和COOKIE请求 ...

  6. Python学习笔记11:函数修饰符

    Python学习笔记11:函数修饰符 Python有很多有趣的特性,其中函数修饰符就是一个. 我们在之前的那个web应用示例中用过如下写法: @web.route('/log') @符号后边的,就是一 ...

  7. Hive学习笔记三之函数操作

    文章目录 5 函数 5.1 系统内置函数 5.2 常用内置函数 5.2.1 空字段赋值 5.2.2 CASE WHEN THEN ELSE END(类似于java中的switch case) 5.2. ...

  8. c++学习笔记内联函数,函数重载,默认参数

    c++学习笔记内联函数,函数重载,默认参数 1 inline内联函数 C++中的const常量可以替代宏常数定义,如: const int A = 3;  #define A 3 C++中是否有解决 ...

  9. 利用抽象工厂创建DAO、利用依赖注入去除客户端对工厂的直接依赖、将有关Article的各种Servlet封装到一个Servlet中(通过BaseServlet进行

    利用抽象工厂创建DAO.利用依赖注入去除客户端对工厂的直接依赖.将有关Article的各种Servlet全部封装到一个Servlet中(通过BaseServlet来进行ArticleServlet方法 ...

最新文章

  1. 怎么用leangoo做需求管理及规划?(产品Backlog、用户故事)
  2. 前端学习(2963):跨域问题
  3. 【java基础知识】java分层思想
  4. 【英语学习】【Daily English】U06 Shopping L01 We are out of pasta.
  5. SAP License:SE16N
  6. 设置PyCharm相同词汇高亮
  7. 重装系统时提示在引导修复时检测到错误怎么办
  8. 用python编写word自动编写离职报告
  9. 从一个简单的main方法执行谈谈JVM工作机制
  10. js 获得较浅的颜色_了解较少的颜色功能
  11. 仿原生安卓文件管理器
  12. 开发软件的步骤是什么
  13. 软件推荐 scrcpy
  14. 【每日微信新闻早报简报】10月11日 星期五
  15. 内嵌模式搭建Hive
  16. oracle rsm 进程,Oracle 10g 的后台进程
  17. 第五章 编码/加密——《跟我学Shiro》
  18. Atcoder Grand Contest 012 B - Splatter Painting解题报告
  19. 加密流量分类-论文6:Learning to Classify A Flow-Based Relation Network for Encrypted Traffic Classification
  20. html调整垂直居中,html元素垂直居中的几种方法

热门文章

  1. Centos6.5部署大众点评CAT
  2. LVS nat 负载均衡实验
  3. static_cast
  4. 【windows8开发】C++开发WinRT组件和JS调用
  5. POJ 1936 All in All
  6. 洛谷P3952 时间复杂度【字符串】【模拟】
  7. Jupyter 安装并配置工作路径[转]
  8. Eclipse 配置SSH 详解
  9. 【word2vec】篇一:理解词向量、CBOW与Skip-Gram等知识
  10. python学习高级篇(part5)--内置函数type