【问题标题】:How to set the 'this' object of a callback function to the container component from a class decorator如何从类装饰器将回调函数的“this”对象设置为容器组件
【发布时间】:2019-02-12 02:30:48
【问题描述】:

您好,我正在尝试为我的服务器服务制作一个类装饰器,以便我可以轻松地在任何组件上共享我的服务, 我有一个名为“onUser”的函数,当我从服务器获取用户数据时,它充当回调 但是尝试访问我在装饰器上调用的 callbach 的“this”表明“this”与容器组件的“this”不同 我错过了什么?谢谢

class decorator

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);
      }
    };
  };
}

component container/callee)

@UserSubscriber()
@Component({
 ...
})
export class AppComponent {
  ...

  onUser(user) {
    console.log(user);

    console.log(this); // this is not the instance of this component
  }
}

【问题讨论】:

  • 尝试将回调定义为箭头函数:onUser = (user) =&gt; { ... }
  • 顺便说一句,您应该将相关代码作为文本包含在问题中,而不是作为图像。
  • 抱歉,这是我第一次在堆栈上发帖 :)

标签: angular typescript typescript-decorator


【解决方案1】:

将您的订阅移动到 ngOnInit 覆盖并在那里使用箭头功能:

constructor.prototype['ngOnInit'] = function (...args) {
  subscription = userService.user$.subscribe(user => { // preserve this
    constructor.prototype.onUser.call(this, user); // call with component context
  });
  if (orgOnInit) {
    orgOnInit.apply(this, args);
  }
};

如果在 ngOnDestroy 钩子中初始化,也会销毁订阅:

constructor.prototype['ngOnDestroy'] = function(...args) {
  if (subscription) {
    subscription.unsubscribe();
  }

  ...
};

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2019-02-11
    • 2019-05-09
    • 2023-02-08
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多