0

I am trying to change a variable to match a JSON incoming from my backend over a WAMP router. However, in my event handler the variable outside is always undefined when i try to console.log() it. Additionally, changes to the variable in the event handler are not applied to the variable outside, and i don't understand why...

This is my service where the Data is supposed to "arrive" from the backend and be changed I can't really create a running stackblitz as the backend data and WAMP is to much to integrate/ mock.

export class HouseService {  
public JSONObject: any; //this variable does not change
// function called to connect to wamp

constructor(){
  this.JSONObject = 'test';  
}

 getWampCon(){
    this.wampConnection.open();
    this.wampConnection.onopen = (session) => {
      console.log('wamp connected');
      session.subscribe('some.wamp.topic', this.onevent1).then(
      (subscription) => {
        console.log('ok, subscribed with ID ' + subscription.id);
      },
      (error) => {
       console.log(error);
      }
   );
  };
  // Event Handler
  onevent1(args, kwargs) {
    console.log('got event:', args, kwargs);
    console.log(this.JSONObject); // returns undefined and i don't get why
    this.JSONObject = args[0];
  }
}

the function

getWampCon() is then called in the display component

I want to get something similiar like the following AngularJS verison:

   function onevent1(args, kwargs) {
      console.log("got event:", args, kwargs);
      var scope = angular.element(document.getElementById('Receiver')).scope();
      scope.$apply(function() {
          scope.showMe(args[0]);
      });
   }

1 Answers1

0

console.log(this.JSONObject); // returns undefined and i don't get why

Because the scope of the "this" keyword it's not the same of the HouseService class. It's an old story about javascript.

Try to to this:

session.subscribe('some.wamp.topic',(args,kwargs)=>{ this.onevent1(args,kwargs);}).then(...

AlbertoZ
  • 154
  • 8