angular-websockets
angular-websockets copied to clipboard
Wait until websocket is opened
Hi,
Is there any way to know from app.component if the websocket is ready, i mean, opened? In the example data are sent to websocket when the user clicks the send button, so websocket had time to connect properly. I'm currently in a scenario where i'm sending data to the websocket on ngOnInit method within a component and i'm facing with the fact that the websocket is not opened yet so, these first messages are lost.
I guess it could be achieved by listen to onopen event but I don't know how :S
create(url:string):Rx.Subject<MessageEvent>{
let ws = new WebSocket(url);
ws.onopen = function(e){
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
}
);
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
console.log('Writing to WS');
ws.send(JSON.stringify(data));
}
else{
console.log('CANNOT write to WS because it is not open yet');
}
}
};
return Rx.Subject.create(observer, observable);
}
}
How could I manage that?
PS: Great work!!