Home > Software engineering >  How add method decorator
How add method decorator

Time:08-08

I want to create the method decorate in angular where I can pass the argument and it will override the result. For example let suppose I have calculation typescript file which look like below.

export class Calculation{
    @multiply(2)
    addOne(number:number) {
        return number 1;
    }        
}

function multiply(param1: number) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        // my code      
    };
}

and I have above "multiply" method decorator where I am passing the argument value as 2 when I will call console.log(new Calculation().addOne(2)) it should return ((2 1)*2) = 6

Can anyone have any suggestion?

CodePudding user response:

If your decorator looks like this, it returns the original result multiplied by two:

export function multiply(factor: number) {
  return function(target: Object, key: string | symbol, descriptor: PropertyDescriptor) {
    originalFunction = descriptor.value
    descriptor.value = (num: number) => {
      originalFunction.call(this as any, num) * factor;
      //                         ^^^^^^
    }
    return descriptor;
  }
}
  • Related