【发布时间】:2019-02-12 02:30:48
【问题描述】:
您好,我正在尝试为我的服务器服务制作一个类装饰器,以便我可以轻松地在任何组件上共享我的服务, 我有一个名为“onUser”的函数,当我从服务器获取用户数据时,它充当回调 但是尝试访问我在装饰器上调用的 callbach 的“this”表明“this”与容器组件的“this”不同 我错过了什么?谢谢
export function UserSubscriber() {
return (constructor: any) => {
const component = constructor.name;
const userService: UserClientService =
InjectorInstance.get<UserClientService>(UserClientService);
let subscription: Subscription;
subscription = userService.user$.subscribe(function(user) {
constructor.prototype.onUser(user);
});
const orgOnInit = constructor.prototype['ngOnInit'];
constructor.prototype['ngOnInit'] = function (...args) {
if (orgOnInit) {
orgOnInit.apply(this, args);
}
};
const orgOnDestroy = constructor.prototype['ngOnDestroy'];
constructor.prototype['ngOnDestroy'] = function(...args) {
subscription.unsubscribe();
if (orgOnDestroy) {
orgOnDestroy.apply(this, args);
}
};
};
}
@UserSubscriber()
@Component({
...
})
export class AppComponent {
...
onUser(user) {
console.log(user);
console.log(this); // this is not the instance of this component
}
}
【问题讨论】:
-
尝试将回调定义为箭头函数:
onUser = (user) => { ... }。 -
顺便说一句,您应该将相关代码作为文本包含在问题中,而不是作为图像。
-
抱歉,这是我第一次在堆栈上发帖 :)
标签: angular typescript typescript-decorator