您可能会在编译后的代码中看到有关装饰器如何工作的见解,例如
编译后的代码如下所示,
ComponentClass = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'component-selector',
templateUrl: 'component.html',
styleUrls: ['component.css'],
providers: [component_service_1.ComponentService]
}),
__metadata('design:paramtypes', [component_service_1.ComponentService])
], ComponentClass);
当角度核心对此进行调查时,它用于Reflect.js
获取有关组件的元数据信息。
要创建自己的装饰器,您可以在下面尝试,
我的自定义装饰器
import "reflect-metadata";
interface ICustomDecoratorMeta{
var1: string
}
export var MyCustomDecorator =
(metadata: <ICustomDecoratorMeta>) => {
return (target) => {
Reflect.defineMetadata("MyCustomDecorator", metadata, target);
}
}
如何使用它,
@MyCustomDecorator({
var1 : "Hello"
})
export class MyClass(){}
// To retrieve metadata you can use below,
var metadata = Reflect.getMetadata('MyCustomDecorator', MyClass);
希望这可以帮助!!