iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 8
1
Modern Web

從巨人的 Tip 看 Angular系列 第 8

[Day 8] 所以我說那個 multi 是?

前幾天有提到 NG_VALIDATORS 這個內建的 DI Token,在我們新增 providers 的時候,用到了 multi 這個屬性,並將其設為 true,雖然知道這個屬性允許多個 provider 使用相同的 DI Token,但我還是不懂 Angular 是一次注入一個實體,是的話,又怎麼決定要注入哪個?還是說,Angular 會一次注入所有實體?

文件這樣說

一下引言內容來自:官方文件

Multiple providers can be associated with a single token in other areas as well. For example, you can register a custom form validator using the built-in NG_VALIDATORS token, and provide multiple instances of a given validator provider by using the multi: true property in the provider object. Angular adds your custom validators to the existing collection.

以及:

Note that the reference to the array returned for a multi provider is shared between all the places where the token is injected. We recommend avoiding mutations of the array (especially for predefined tokens) as it may lead to unexpected behavior in other parts of the app that inject the same token. You can prevent the value from being mutated by setting its type to ReadonlyArray.

來幫各位畫個重點喔:

  1. 當使用 NG_VALIDATORS 這個 DI Token 時,Angular 會將自訂的 validator 加入已存在的集合。
  2. Multi provider 會回傳一個 Array。
  3. 不要對注入的 Array 做操作,會發生什麼事誰都不知道。

OK,單就字面上的意思來看,Angular 會把一整個陣列都送給那個要求注入的那個物件。

來看看實際上執行的結果是怎樣:

export const MULTI_TOKEN = new InjectionToken(
  'Hey im new token!'
);

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [
    {
      provide: MULTI_TOKEN,
      useValue: 'OK',
      multi: true,
    },
    {
      provide: MULTI_TOKEN,
      useValue: 'OOOOOK',
      multi: true,
    },
  ],
})
export class AppComponent {
  constructor(@Inject(MULTI_TOKEN) public x: any) {
    console.log(`⚡: AppComponent -> constructor -> x`, x);
  }
}

↑ Block 1

Block 1 的程式碼非常簡單,先建立一個 DI Token 叫做 MULTI_TOKEN,接著在 @Component 修飾詞身上新增 providers 屬性,放入兩個提供不同字串的 provider,最後就是直接在 constructor 上注入。

就這樣,沒了!

而這段程式碼的執行結果會是:

https://ithelp.ithome.com.tw/upload/images/20200923/20129148l7qtE8alt3.png

對啦你沒看錯,Angular 真的會給你一整個陣列喔!

之後再來好好的深入探討一下在這個 multi: true 的屬性背後,究竟又發生了什麼事。

第 8 天啦?

以下按照入團順序列出我們團隊夥伴的系列文章!


上一篇
[Day 7] FormGrop、FormControlName 與 FormControl 之間的秘密
下一篇
[Day 9] 事件繫結好方便,那你知道 EVENT_MANAGER_PLUGINS 嗎?
系列文
從巨人的 Tip 看 Angular30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言