我试图将自定义方法装饰器添加到角度组件函数以添加一些日志记录功能。
我正在内部装饰的组件方法调用了我注入到组件中的角度服务函数。不幸的是,在运行代码时,注入的服务被定义为未定义。
下面的示例代码:
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
,您不应使用传播运算符。如果要使用它,则必须使用call
:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句