如何通过类装饰器将回调函数的“ this”对象设置为容器组件

时间:2019-02-12 02:30:48

标签: angular typescript typescript-decorator

嗨,我正在尝试为服务器服务创建类装饰器,以便我可以轻松地在任何组件上共享服务, 我有一个名为“ 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
  }
}

1 个答案:

答案 0 :(得分:0)

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

  ...
};