Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 4/socket.io access global variables and function calling

I have to use simple socket client for angular 4 frontend. When I receive data to socket.on can't assign that data to global variables & can't call any function inside socket.on.

public sessionId;

constructor(){

var socket = io.connect('http://**.***.***.***:****');

socket.on('connect', function (data) {
  console.log('user connected');
  socket.emit('add user', { userId: uid });
});

socket.on('create channel', function (data) {

  console.log(data);
  this.sessionId = data.sessionId;    //error
  this.function();                    //error

  socket.emit('feedback', { received: true });
});
}


function(){}
like image 769
Amith Avatar asked May 04 '26 19:05

Amith


1 Answers

In my case, I create new Observable and handle socket event. and a module subscribe that observable and call function.

That code is this :

  getSocketEvent(){

    let observable = new Observable(observer => {
      this.socket.on('event', (data) => {
        observer.next(data);
      });
      return () => {
        // this.socket.disconnect();
      };
    });
    return observable;
  }


  initService(){

    this.getSocketEvent().subscribe(data => {
      console.log('socket data :',data);

      //do something HERE
    });
  }
like image 69
Jihoon Kwon Avatar answered May 06 '26 08:05

Jihoon Kwon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!