3

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(){}

1 Answer 1

1

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
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.