脚本宝典收集整理的这篇文章主要介绍了Angular 2 Decorators - 3,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在 Angular 2 Decorators part -1 和 part -2 文章中,我们介绍了 Decorator 的分类和 Angular 2 常见的内置装饰器,并且我们深入分析了 componentDecorator 内部工作原理。此外,我们还发现在 TyPEDecorator 类装饰器内部,使用了 Reflect 对象提供的 getOwnMetadata 和 defineMetadata 方法,实现 metadata 信息的读取和保存。具体可参照下图:
Angular 2 metadata 类型分为:
(备注:其中 design:paramtypes 和 parameters metadata 类型是用于依赖注入)
接下来我们来看一下具体示例:
以上代码成功运行后,在浏览器控制台中,输入 window['__core-js_shared__'] 即可查看 AppComponent 相关连的 metadata 信息:
示例代码
import { Component, Inject, ViewChild, HostListener, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1 #greet> Hello {{ name }} </h1>`,
})
export class AppComponent {
name = 'Angular';
@ViewChild('greet')
private greetDiv: ElementRef;
@HostListener('click', ['$event'])
onClick($event: any) {
console.dir($event);
}
constructor(public appService: AppService,
@Inject(CONFIG) config: any) {
}
}
编译后的 ES 5 代码片段:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {...};
var __metadata = (this && this.__metadata) || function (k, v) {...};
var __param = (this && this.__param) || function (paramIndex, decorator) {...};
var AppComponent = (function () {
// AppComponent构造函数
function AppComponent(appService, config) {
this.appService = appService;
this.name = 'Angular';
}
AppComponent.prototype.onClick = function (event) {
console.dir(event);
};
__decorate([
core_1.ViewChild('greet'),
__metadata('design:type', core_1.ElementRef) // 标识greetDiv属性类型
], AppComponent.prototype, "greetDiv", void 0);
__decorate([
core_1.HostListener('click', ['$event']),
__metadata('design:type', Function), // 标识onClick类型
__metadata('design:paramtypes', [Object]), // 标识onClick参数类型
__metadata('design:returntype', void 0) // 标识返回值类型
], AppComponent.prototype, "onClick", null);
AppComponent = __decorate([
core_1.Component({ // 调用ComponentDecoratorFactory返回TypeDecorator
selector: 'my-app',
template: "<h1 #greet> Hello {{ name }} </h1>",
}),
__param(1, core_1.Inject(config_1.CONFIG)),
__metadata('design:paramtypes', [app_service_1.AppService, Object])
], AppComponent);
return AppComponent;
}());
exports.AppComponent = AppComponent;
总结
本文主要介绍了 angular 2 中 metadata 分类,并通过一个实际的案例,阐述了 Angular 2 内部装饰器与 metadata 之间的映射关系。window['__core-js_shared__'] 对象内保存的 metadata 信息,是 Angular 2 依赖注入的基础,也为我们揭开了 Angular 2 依赖注入神秘的面纱。
以上是脚本宝典为你收集整理的Angular 2 Decorators - 3全部内容,希望文章能够帮你解决Angular 2 Decorators - 3所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。