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(){}
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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With