【发布时间】:2019-02-03 21:06:52
【问题描述】:
我正在创建一个自定义装饰器,它将在 RxJS 事件上运行装饰函数。
到目前为止一切顺利:当函数实际运行时,我的问题出现了:this 对象的上下文丢失了。
过去一天我一直在寻找解决方案,但似乎找不到。
Here is a stackblitz 重现问题。目标是在控制台中看到来自this.name 的Angular。
【问题讨论】:
标签: angular typescript decorator aop
我正在创建一个自定义装饰器,它将在 RxJS 事件上运行装饰函数。
到目前为止一切顺利:当函数实际运行时,我的问题出现了:this 对象的上下文丢失了。
过去一天我一直在寻找解决方案,但似乎找不到。
Here is a stackblitz 重现问题。目标是在控制台中看到来自this.name 的Angular。
【问题讨论】:
标签: angular typescript decorator aop
我在地图中传达方法上下文的自定义方式:)
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));
});
}
}
}
【讨论】:
请尝试以下代码,它会起作用。听说您只将其更改为构造函数。
function HelloWorld(): ClassDecorator {
return function(constructor) {
constructor.prototype.HelloWorld.apply(new constructor(), null);
};
}
【讨论】:
Hello world, name is HelloComponent
在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);
}
});
}
}
}
【讨论】:
我看到您正在尝试在装饰器中调用装饰类实例的方法。然而,类装饰器不是这样工作的。它们在类被定义时被调用,而不是在它被实例化时被调用,所以你不能用你的类的实例调用任何东西。
这是您的updated stackblitz。我正在扩展您的类并在扩展类的构造函数中调用该方法,以便在实例化装饰类的对象时调用它。
【讨论】:
super 调用中?我试过constructor.arguments,但它抛出'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
...args并调用super(...args)
args?