【发布时间】:2020-09-14 19:42:44
【问题描述】:
我通过以下方式在 typescript/angular 中使用装饰器
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 实例链接的最佳方法是什么?
【问题讨论】:
-
我不认为你可以在实例级别修改东西,但你应该可以在原型级别进行,也就是说,装饰器可以将那个道具变成原型上的getter
@Field({source: MyClass.prototype.myFn)或@Field({source: 'myFn')
标签: angular typescript typescript-decorator