Typescript 自定义装饰器:上下文

Typescript custom decorators : context of this

我正在创建一个自定义装饰器,它将 运行 在 RxJS 事件上装饰函数。

到目前为止一切顺利:当函数实际上是 运行 时,我的问题就来了:this 对象的上下文丢失了。

过去一天我一直在寻找解决方案,但似乎找不到。

Here is a stackblitz 重现问题。目标是在控制台中看到来自 this.nameAngular

我看到您正在尝试在装饰器中对 decorated class 的实例调用一个方法。但是,class 装饰器不是这样工作的。它们在 class 被 定义 时被调用,而不是在它被实例化时被调用,所以你不能用你的 class.

的实例调用任何东西

这是你的updated stackblitz。我正在扩展您的 class 并调用扩展 class 的构造函数中的方法,以便在实例化装饰 class 的对象时调用它。

https://netbasal.com/inspiration-for-custom-decorators-in-angular-95aeb87f072c 没有

constructor.prototype.HelloWord.apply(this, null);

只需评论您的应用工作的行

cosntructor.prototype 正在使用 ngOnInit、ngOnChanges...

例如页面显示为

import { environment } from "../environments/environment";
export function NgLog() : ClassDecorator {
  return function ( constructor : any ) {
    if( !environment.production ) {
      // You can add/remove events for your needs
      const LIFECYCLE_HOOKS = [
        'ngOnInit',
        'ngOnChanges',
        'ngOnDestroy'
      ];
      const component = constructor.name;

      LIFECYCLE_HOOKS.forEach(hook => {
        const original = constructor.prototype[hook];

        constructor.prototype[hook] = function ( ...args ) {
          console.log(`%c ${component} - ${hook}`, `color: #4CAF50; font-weight: bold`, ...args);
          original && original.apply(this, args);
        }
      });
    }

  }
}

请尝试下面的代码,它会起作用。听说您只将其更改为构造函数。

function HelloWorld(): ClassDecorator {
  return function(constructor) {
    constructor.prototype.HelloWorld.apply(new constructor(), null);
  };
}

我在地图中传达方法上下文的自定义方式:)

return class extends constructor {
            constructor(...args) {
                super(...args);
                if(constructor.processCallbackMap){
                    Array.from(constructor.processCallbackMap).map(([key, value]) = {
                        constructor.processCallbackMap.set(key, value.bind(this));
                    });
                }
            }
        }