網站首頁 編程語言 正文
下面是 SAP 電商云 Spartacus UI 兩個 Angular Service 類,都加上了 @Injectable
的注解,區別就在于是否具有輸入參數 providedIn
:
@Injectable() 裝飾器指定 Angular 可以在 DI 系統中使用這個類。 這個注解的輸入元數據,providedIn: ‘root’,意味著被注解的 Angular service 類,在整個應用程序中都是可見的。
當將服務(提供者)注入到我們的組件/服務中時,通過構造函數中的類型定義來指定我們需要的提供者。下面是一個例子:
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。
對于 JavaScript 開發人員來說,上面的工作方式或許有些神奇。類型定義是特定于 TypeScript 的,所以我們編譯的 JavaScript 代碼理論上應該不知道在瀏覽器中運行它時我們的 http 參數是什么。
在我們的 tsconfig.json 文件中,我們將 emitDecoratorMetadata 設置為 true。 這會將有關參數類型的元數據發送到我們編譯的 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]);
所以本質上,@Component 裝飾器被轉換為普通的 ES5,并且一些額外的元數據通過 __decorate 賦值提供。 這反過來告訴 Angular 查找 Http 令牌并將其作為第一個參數提供給組件的構造函數 - 將其分配給 this.http:
function ExampleComponent(http) {
this.http = http;
}
原文鏈接:https://blog.csdn.net/i042416/article/details/125852967
相關推薦
- 2022-09-16 Oracle查看表空間使用率以及爆滿解決方案詳解_oracle
- 2022-05-27 C++實現數獨快速求解_C 語言
- 2022-07-16 Electron項目打包
- 2023-05-11 Oracle怎么刪除數據,Oracle數據刪除的三種方式_oracle
- 2022-05-27 go語言實現兩個協程交替打印_Golang
- 2022-06-02 slf4j Logger使用{}占位符輸出日志
- 2021-12-01 阻止谷歌瀏覽器彈出記住密碼的彈框
- 2022-09-19 利用Python實現批量打包程序的工具_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支