Angular 依赖注入学习笔记之工厂函数的用法
網(wǎng)址:https://angular.institute/di
We can transfer any data through our apps, transform it and replace it.
我們能傳遞任何數(shù)據(jù)到我們的應(yīng)用里,改變其形態(tài),并且替換。
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 能在瀏覽器環(huán)境下運行。但是如果在 SSR 下 build 應(yīng)用,或者用 nodejs precompile,那么這些對象在新的環(huán)境下不再可用。
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.
依賴注入機(jī)制管理應(yīng)用的依賴。對于 Angular 開發(fā)者來說,有兩種操作:
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.
當(dāng)我們試圖在 DI 樹里第一次獲取實例時,Angular 負(fù)責(zé)實例化。
Providing value is normally used with InjectionToken. This object is like a key for DI mechanism.
我們也可以用依賴注入提供常量,通常借助 InjectionToken. 這個令牌類似依賴注入機(jī)制中的 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 依賴注入機(jī)制,“你維護(hù)的資源里,有針對這個 key 的值嗎?”
看個具體的例子。
export const API_URL = new InjectionToken<string>('The URL of API');在 api-url.token.ts 里,我們從 @angular/core 里導(dǎo)入了標(biāo)準(zhǔn)的 InjectionToken 構(gòu)造器,其類型為 string,描述信息為:The URL of API.
在 app.module.ts 里,導(dǎo)入這個 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 樹上的任意層次結(jié)構(gòu)里,替換 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 代碼里編寫一些業(yè)務(wù)邏輯,執(zhí)行一些數(shù)據(jù)結(jié)構(gòu)變換的操作。
看個例子:
定義一個函數(shù):
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)); }構(gòu)造一個 Observable 對象,當(dāng)鍵盤被按下時,從 KeyboardEvent 里解析出具體哪一個鍵被按下,然后將 key 值通過 Observable 對象返回。
這個函數(shù)被當(dāng)成一個工廠函數(shù),本身接收類型為 Document 的參數(shù),這個參數(shù)就是其依賴。
我們通過下列的語法,將名為 PRESSED_KEY 的令牌,和該工廠函數(shù)綁定在一起。
@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的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的Angular 依赖注入学习笔记之工厂函数的用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 荒野猎手冈布奥怎么获得
- 下一篇: 塞尔达传说荒野之息黄金人马位置(为什么游