当前位置: 代码网 > it编程>前端脚本>AngularJs > Angular @Injectable注解的工作原理解析

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

2024年05月18日 AngularJs 我要评论
正文下面是 sap 电商云 spartacus ui 两个 angular service 类,都加上了 @injectable 的注解,区别就在于是否具有输入参数 providedin:@injec

正文

下面是 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注解的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com