天天看點

Angular 依賴注入學習筆記之工廠函數的用法

網址: 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 開發者來說,有兩種操作:

提供資料到依賴注入樹中

從依賴注入樹中擷取資料

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');
      
Angular 依賴注入學習筆記之工廠函數的用法
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 代碼裡編寫一些業務邏輯,執行一些資料結構變換的操作。

看個例子:

Angular 依賴注入學習筆記之工廠函數的用法
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)
  );
}
      
Angular 依賴注入學習筆記之工廠函數的用法
Angular 依賴注入學習筆記之工廠函數的用法

繼續閱讀