【发布时间】:2018-11-13 18:36:38
【问题描述】:
我正在尝试将自定义方法装饰器添加到角度组件函数中以添加一些日志记录功能。
我在内部装饰的组件方法调用了我注入到组件中的角度服务函数。 不幸的是,在运行代码时,注入的服务被认为是未定义的。
下面的示例代码:
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”错误。 关于如何让它发挥作用的任何想法?
【问题讨论】:
-
我相信如果你有这样的装饰器功能,你应该去掉大括号,所以只有
@myCustomDecorator -
@PierreDuc 好点 - 但注射剂的潜在问题仍然存在......
-
我会发布一个比代码更容易阅读的答案:)
标签: angular typescript decorator