当前位置: 首页 > Web前端 > HTML5

Angular@Injectable注解工作原理分析

时间:2023-04-05 15:51:35 HTML5

以下是SAP电商云SpartacusUI的两个AngularService类,都使用了@Injectable注解。区别在于是否有传入参数providedIn:@Injectable()decorator指定Angular可以在DI系统中使用这个类。此注解的输入元数据providedIn:'root'意味着被注解的Angular服务类在整个应用程序中都是可见的。在我们的组件/服务中注入服务(提供者)时,我们通过构造函数中的类型定义来指定我们需要的提供者。这是一个例子:import{Component}from'@angular/core';import{Http}from'@angular/http';@Component({selector:'example-component',template:'

Iamacomponent
'})classExampleComponent{constructor(privatehttp:Http){//使用`this.http`是Httpprovider}}这里的类型定义是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';varExampleComponent=(function(){functionExampleComponent(http){this.http=http;}returnExampleComponent;})();ExampleComponent=__decorate([Component({选择器:'example-component',template:'
我是一个组件
',}),__metadata('design:paramtypes',[Http]),],ExampleComponent);从这里,我们可以看到编译后的代码,知道http是angular/http提供的@Http服务——它作为装饰器添加到我们的类中:__metadata('design:paramtypes',[Http]);所以本质上,@Component装饰器被转换为带有一些额外的普通ES5的元数据,通过__decorate赋值提供。这反过来告诉Angular查找Http令牌并将其作为组件构造函数的第一个参数提供——将其分配给this.http:functionExampleComponent(http){this.http=http;}