Angular @Injectable注解的工作原理解析
正文
下面是 SAP 电商云 Spartacus UI 两个 Angular Service 类,都加上了 @Injectable
的注解,区别就在于是否具有输入参数 providedIn
:
@Injectable() 装饰器
@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。
浏览器中运行时的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; }
以上就是Angular @Injectable 注解的工作原理解析的详细内容,更多关于Angular @Injectable注解的资料请关注脚本之家其它相关文章!
相关文章
AngularJs Dependency Injection(DI,依赖注入)
本文主要介绍AngularJs Dependency Injection,这里整理了详细资料及示例代码有兴趣的小伙伴可以参考下2016-09-09Angular.js项目中使用gulp实现自动化构建以及压缩打包详解
基于流的前端自动化构建工具,利用gulp可以提高前端开发效率,特别是在前后端分离的项目中。下面这篇文章主要给大家介绍了关于在Angular.js项目中使用gulp实现自动化构建以及压缩打包的相关资料,需要的朋友可以参考下。2017-07-07
最新评论