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

安东诉B

我试图将自定义方法装饰器添加到角度组件函数以添加一些日志记录功能。

我正在内部装饰的组件方法调用了我注入到组件中的角度服务函数。不幸的是,在运行代码时,注入的服务被定义为未定义。

下面的示例代码:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

NestJs - 从自定义装饰器内的服务调用方法

Angular2:是否使用自定义装饰器或注释将提供程序注入组件?

Angular 5:在自定义装饰器函数内部使用服务

Angular-从组件调用服务的方法返回未定义

React 自定义组件参数未定义

将$ http服务封装在自定义服务中时,出现自定义方法未定义错误

无服务器自定义授权者结果未定义

Angular2注入的自定义服务未定义

使用 React Hook 表单的表单显示自定义输入组件字段未定义

Angular 7:自定义类装饰器销毁组件范围

Angular 4-验证器自定义函数,未定义

TypeError:添加自定义验证器时,无法读取未定义Angular的属性'indexOf'

使用 http 服务的角度自定义验证 - 无法读取未定义的属性

打字稿方法装饰器:这是未定义的

Angular 2自定义装饰器取消订阅策略

使用Draper装饰器的未定义方法link_to_edit

Django自定义权限方法或装饰器

应用函数并使用装饰器检查自定义异常

我在组件 Angular 8 中调用服务未定义

装饰实例上的未定义方法

如何使用Jasmine(Angular JS)对自定义装饰器进行单元测试

Tornado 中的自定义装饰器

TypeScript中的自定义装饰器

Angular 2自定义装饰器(适用于RC4之后的版本)提供了“多个组件”

Angular 单元测试自定义验证器无法读取未定义的属性(读取“dobLengthValidator”)

Vue 2 自定义组件值总是“未定义”

Sencha Touch-为什么在我的自定义组件中未定义此功能?

Java中的自定义组件未定义构造函数

无法读取未定义的属性“ containerColor”(产生反应式自定义组件)