0

i cant access a global variable in type script in an other method.

As i have initialized this "initiatorOffer" global variable in this methode

peerx.on('signal', function(data)
{

   console.log("1");

   console.log(JSON.stringify(data));

   this.targetpeer = data;

   **this.initiatorOffer = JSON.stringify(data);  // i have initialized there**

   console.log(this.initiatorOffer);


}

but when i get this value in other method on same file which is:

this._chatservice.clientconnected().subscribe(data => {

   **console.log(this.initiatorOffer);** // getting value

})

i get the undefined value. why is that? as this variable is global.

this.chatservice.clientconnected() method called when i get a response from server.

Anjil Dhamala
  • 1,381
  • 2
  • 17
  • 28
Adil
  • 117
  • 1
  • 1
  • 8
  • console log your 'this' in both callback function of 'on()' and subscribe function of 'clientConnected()'. See if they are similar. – Anjil Dhamala Aug 16 '18 at 15:42
  • they are not similar. so what can i do to fix this – Adil Aug 16 '18 at 17:45
  • I'd suggest reading this: https://www.vinta.com.br/blog/2015/javascript-lambda-and-arrow-functions/ if you change your callback function to () => {} instead of function() {}, I believe you'll have access to the same context 'this'. – Anjil Dhamala Aug 16 '18 at 18:12

2 Answers2

0

I think that the problem that Angular don't take account the changes in your peerx.on('signal', function(data). You can try using ngZone https://angular.io/api/core/NgZone#ngzone

peerx.on('signal', function(data)
{
   this.ngZone.run(() => {
      console.log("1");
      console.log(JSON.stringify(data));
      this.targetpeer = data;
      this.initiatorOffer = JSON.stringify(data);  // i have initialized there**
      console.log(this.initiatorOffer);
   })
})
Eliseo
  • 29,422
  • 4
  • 13
  • 37
0

You should convert the function to arrow function as follows:

peerx.on('signal', (data) => {
....
// here you can access 'this' instance
});

This is an arrow function. Arrow functions are a short syntax, introduced by ECMAScript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences.

For example, they do not bind their own values of this.

Refer to this link:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Pang
  • 8,605
  • 144
  • 77
  • 113
Bhimashankar Mantur
  • 229
  • 1
  • 3
  • 12