欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular?@Injectable注解的工作原理解析

 更新時間:2023年06月15日 15:05:46   作者:JerryWang_汪子熙  
這篇文章主要為大家介紹了Angular?@Injectable注解的工作原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

下面是 SAP 電商云 Spartacus UI 兩個 Angular Service 類,都加上了 @Injectable 的注解,區(qū)別就在于是否具有輸入?yún)?shù) providedIn

@Injectable() 裝飾器

@Injectable() 裝飾器指定 Angular 可以在 DI 系統(tǒng)中使用這個類。

這個注解的輸入元數(shù)據(jù),providedIn: 'root',意味著被注解的 Angular service 類,在整個應用程序中都是可見的。

當將服務(提供者)注入到我們的組件/服務中時,通過構(gòu)造函數(shù)中的類型定義來指定我們需要的提供者。下面是一個例子:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
  selector: 'example-component',
  template: '<div>I am a component</div>'
})
class ExampleComponent {
  constructor(private http: Http) {
    // use `this.http` which is the Http provider
  }
}

這里的類型定義是 Http(注意大寫的 H),Angular 會自動將其分配給 http。

瀏覽器中運行時的http參數(shù)

對于 JavaScript 開發(fā)人員來說,上面的工作方式或許有些神奇。類型定義是特定于 TypeScript 的,所以我們編譯的 JavaScript 代碼理論上應該不知道在瀏覽器中運行它時我們的 http 參數(shù)是什么。

在我們的 tsconfig.json 文件中,我們將 emitDecoratorMetadata 設置為 true。 這會將有關(guān)參數(shù)類型的元數(shù)據(jù)發(fā)送到我們編譯的 JavaScript 輸出中的裝飾器中。

讓我們看看上面列舉的 TypeScript 代碼,實際上被編譯成什么(為了清楚起見,我保留了 ES6 導入):

import { Component } from '@angular/core';
import { Http } from '@angular/http';
var ExampleComponent = (function() {
  function ExampleComponent(http) {
    this.http = http;
  }
  return ExampleComponent;
})();
ExampleComponent = __decorate(
  [
    Component({
      selector: 'example-component',
      template: '<div>I am a component</div>',
    }),
    __metadata('design:paramtypes', [Http]),
  ],
  ExampleComponent
);

從這里,我們可以看到編譯后的代碼,知道 http 就是 @angular/http 提供的 Http 服務 - 它被添加為我們的類的裝飾器:

__metadata('design:paramtypes', [Http]);

所以本質(zhì)上,@Component 裝飾器被轉(zhuǎn)換為普通的 ES5,并且一些額外的元數(shù)據(jù)通過 __decorate 賦值提供。 這反過來告訴 Angular 查找 Http 令牌并將其作為第一個參數(shù)提供給組件的構(gòu)造函數(shù) - 將其分配給 this.http:

function ExampleComponent(http) {
  this.http = http;
}

以上就是Angular @Injectable 注解的工作原理解析的詳細內(nèi)容,更多關(guān)于Angular @Injectable注解的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論