Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sockjs with Angularjs - Error: INVALID_STATE_ERR

I'm trying Angularjs with sockjs and I'm using this to help: https://github.com/bendrucker/angular-sockjs

I would like to send some data via sockjs on page load but I'm getting Error: INVALID_STATE_ERR on the client side when I try to make the following call:

socket.send("test data");

I assume this is because Sockjs isn't "ready" yet. If I wrap it in a $timeout it works if the delay is big enough. 1000 works but 100 doesn't.

$timeout(function() {
  socket.send("test");
}, 1000);

This is obviously a hack and I wondered how I can detect when sockjs is ready so that I can then make the call.

like image 303
tommyd456 Avatar asked Jun 14 '26 07:06

tommyd456


1 Answers

You should use the setHandler method and provide a callback for 'open'. It'll be safe to send messages there. The service is pretty light and really only intended to ensure that the three SockJS client callbacks (onopen, onclose, onmessage) are called inside a digest cycle. If you wanted, you could easily use it to build a more complex service that among many possibilities could:

  • queues sent messages when the socket is closed and sends them when it opens
  • returns a $q promise that resolves when the socket opens
like image 168
Ben Drucker Avatar answered Jun 16 '26 20:06

Ben Drucker



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!