【问题标题】:TypeScript decorator for setTimeout() function用于 setTimeout() 函数的 TypeScript 装饰器
【发布时间】:2017-11-06 10:11:25
【问题描述】:

我已经开始学习如何在我的应用程序中实现 TypeScript 装饰器。 所以我从setTimeout开始。这是一个方法装饰器,它会在一段时间后执行方法。

例如:

@Decorators.timeout()
 public someMethod () {}

这是我的实现:

export class Decorators {

  public static timeout (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>): any {

    let originalMethod = descriptor.value;
    let decArguments = arguments;

    descriptor.value = function Timeout () {

        setTimeout(() => {

          originalMethod.apply(this, decArguments);

        }, 2000);
    };

    return descriptor;

  }

}

这是我遇到的错误:

提供的参数与调用目标的任何签名都不匹配

可能是什么问题?

【问题讨论】:

    标签: javascript angular typescript angular-decorator


    【解决方案1】:

    您的Timeout() 函数中缺少args,您应该将这些args 传递给原始方法:

    descriptor.value = function Timeout (...args) {
    
        setTimeout(() => {
    
          originalMethod.apply(this, args);
    
        }, 2000);
    };
    

    你应该删除这一行,因为它没有做任何事情:

    let decArguments = arguments;
    

    【讨论】:

      【解决方案2】:

      您可以查看 utils-decorators 库中的延迟装饰器: 这是文档的链接:https://github.com/vlio20/utils-decorators#delay-method

      这里是实现:https://github.com/vlio20/utils-decorators/blob/master/src/delay/delay.ts

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2019-07-23
        • 2021-04-22
        • 2015-10-23
        • 2022-08-15
        • 2021-07-15
        • 2018-06-08
        相关资源
        最近更新 更多