我正在尝试将自定义方法装饰器添加到 Angular 组件函数以添加一些日志记录功能。
我在内部装饰的组件方法调用了我注入(inject)到组件中的 Angular 服务函数。 不幸的是,在运行代码时,注入(inject)的服务被认为是未定义的。
示例代码如下:
function myCustomDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalValue = descriptor.value;
descriptor.value = function(...args: any[]) {
const result = originalValue.apply(target, ...args);
//Do some other stuff
return result;
}
return descriptor;
}
@Component()
class myComponentClass implements OnInit {
constructor(private myService: MyService) {}
ngOnInit() {
this.functionIWantToDecorate();
}
@myCustomDecorator
private functionIWantToDecorate() {
this.myService.someServiceFunction();
}
}
导致“无法调用未定义的 someServiceFunction”错误。 关于如何让它发挥作用的任何想法?
最佳答案
如果您立即从装饰器返回描述符,则不应使用大括号 ()
。 this
上下文也丢失了,请尝试使用描述符值中的 this
。除此之外,当你使用 apply
时,你不应该使用扩展运算符。如果你想使用它,你必须使用调用
:
function myCustomDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalValue = descriptor.value;
descriptor.value = function(this: Function, ...args: any[]) {
const result = originalValue.call(this, ...args);
// or --> const result = originalValue.apply(this, args);
//Do some other stuff
return result;
}
return descriptor;
}
关于使用自定义 TS 装饰器的组件方法中未定义 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50680351/