0

Hi i am trying to make a class decorator for my server services so that i can share my services with ease on any component, I have a func called 'onUser' that is acting as a callback when ever i get the user data from the server but trying to access 'this' to the callbach that i call on the decorator shows that 'this' is different to the 'this' of the container component what am i missing? thanks

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
  }
}
yurzui
  • 205,937
  • 32
  • 433
  • 399
Adamson Vispo
  • 23
  • 1
  • 3

1 Answers1

0

Move your subscription inside ngOnInit override and use arrow function there:

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

Also destroy subscription if it is initialized in ngOnDestroy hook:

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

  ...
};
yurzui
  • 205,937
  • 32
  • 433
  • 399