Angular Typescript装饰器和此上下文
我在typescript/angular中以以下方式使用装饰器Angular Typescript装饰器和此上下文,angular,typescript,typescript-decorator,Angular,Typescript,Typescript Decorator,我在typescript/angular中以以下方式使用装饰器 export function Field({source}){ return (target, property) => { // Some code here } } 那么我想这样使用它 export class MyClass { constructor(private myService: MyService) {} @Field({source: () => this.myFn(
export function Field({source}){
return (target, property) => {
// Some code here
}
}
那么我想这样使用它
export class MyClass {
constructor(private myService: MyService) {}
@Field({source: () => this.myFn()})
myProp: string;
private myFn() {
// another code
return this.myService.get()
}
}
显然,上下文是错误的,“this”并不是指MyClass的实例。
将此上下文与MyClass实例链接的最佳方式是什么?您可以使用迂回方法访问装饰器中的实例,具体取决于您尝试执行的操作。在下面的示例中,每次设置属性时都会调用传递给装饰器的函数 decorator将同时处理属性和字段。如果要修饰字段,则会修改目标的原型,并将该字段转换为具有隐藏备份变量的属性,以存储属性值 请注意,它如何不使用箭头函数来定义getter和setter。这就是在设置属性/字段时检索实例的方式。就我个人而言,我经常使用箭头函数,以至于我忘记了这样的事情甚至是可能的,直到我尝试了它
function Field(srcFunc) {
return function (target: any, propertyKey: string, descriptor?: PropertyDescriptor) {
if (descriptor == null) {
const backingKey = `__${propertyKey}`;
Object.defineProperty(target, backingKey, { enumerable: false, writable: true });
Object.defineProperty(target, propertyKey, {
configurable: true,
enumerable: true,
get: function() {
return this[backingKey];
},
set: function(value) {
this[backingKey] = value;
srcFunc.call(this);
}
});
}
else {
const setOriginal = descriptor.set;
descriptor.set = function(value) {
setOriginal.call(this, value);
srcFunc.call(this);
}
}
}
}
export class MyClass {
@Field(MyClass.prototype.myFn)
myProp: string;
private myFn() {
// another code
}
}
我不认为您可以在实例级别修改东西,但您应该能够在原型级别进行修改,也就是说,装饰程序可以将该道具转换为原型
@字段({source:MyClass.prototype.myFn)
或@字段({source:'myFn')上的getter
谢谢,这会起作用。但是,它不会改变此上下文,也不会在更具体的情况下起作用。我更新了我的问题以描述问题所在。即使我将@Field({source:MyClass.prototype.myFn})放在myFn方法中“this”仍然没有设置。我希望我知道具体的情况。但是我知道没有办法直接在decorator工厂函数中获取上下文,所以我提出的任何东西都有点像钻机。