使用自定义 TS 装饰器的组件方法中未定义 Angular 服务

标签 angular typescript decorator

我正在尝试将自定义方法装饰器添加到 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/

相关文章:

Angular Material 菜单模块 : Export of name 'matMenu' not found

angular - 类型 never 上不存在属性 "url"?

Angular httpClient返回对象上不存在的属性

typescript - 是否可以使用现有的 JavaScript 对象作为 TypeScript 中的类型?

typescript - 如何访问 : K extends keyof T, T[K] 的嵌套类型,例如T[K] ["someSubField"]

javascript - 如何按顺序执行一组 Observable,仅在前一个 Observable 完成后才执行下一个?

visual-studio-2012 - 如何改进我的 Visual Studio 2012 Typescript 工作流?

python - 如何将一个函数的重写一般地应用于 python 中的多个类?

python - 使用相同的装饰器路由到 view_func "flask"

python - 具有多个 View 参数的 Django 装饰器