Gili Yaniv
Gili Yaniv

Reputation: 3211

Access method params through decorators

Iv'e started to read about creation of decorators and how to use them. I was wondering if there's a way for me the access the wrapped method arguments inside the decorator function.

For example, I would like to create a decorator the log's the method name and the supplied arguments. So far I only managed to access the method name.

  export function logger(target, propertyKey) {
    console.log(propertyKey); //Method name
  }

  @logger
  private fetchData(param) {
   ////
  }

Is there a way for me the access the "param" of the 'fetchData' method inside the decorator?

Thanks in advance.

EDIT:

Solved, Link to working example

Upvotes: 2

Views: 2212

Answers (1)

Estus Flask
Estus Flask

Reputation: 222344

target is class prototype. In order for method parameters to be accessed during call, a method should be replaced with a wrapper:

  export function logger(target, propertyKey, descriptor) {
    const originalFn = target[propertyKey];
    descriptor.value = function(param) {
      console.log(param);
      return originalFn.call(this, param);
    };
  }

  ...
  @logger
  private fetchData(param) {}
  ...

Upvotes: 3

Related Questions