Search code examples
angulartypescriptdecoratoraop

Typescript custom decorators : context of this


I am creating a custom decorator that will run decorated functions on RxJS events.

So far so good : my issue comes when the function is actually ran : the context of the this object is lost.

I've been looking for a solution for the past day but I can't seem to find it.

Here is a stackblitz reproducing the issue. The goal is to see Angular in the console, coming from this.name.


Solution

  • I see you're trying call a method on the instance of decorated class in your decorator. However, class decorators do not work this way. They are called when the class is defined, not when it's instantiated, so you cannot call anything with instances of your class.

    Here's your updated stackblitz. I'm extending your class and calling the method in the constructor of the extended class, so that it is called whenever objects of the decorated class are instantiated.