关于angular:Angular-Injectable-注解的工作原理浅析

10次阅读

共计 1372 个字符,预计需要花费 4 分钟才能阅读完成。

上面是 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;}
正文完
 0