Utilizing web sockets within my AngularJS application has been a great addition.
However, I encountered an issue where the web socket connection closes when a user logs out. Upon the user logging back in, I need to reconnect the web socket.
The current setup involves housing the web socket within a service, with the following simplified code:
angular.module('myApp').factory("SubscriptionFactory", function () {
var Service = {};
var ws = new WebSocket("ws://127.0.0.1:8000");
/* Omitting WS methods (onopen, onmessage, etc.) for brevity */
Service.reestablishConnection = function() {
// Reestablishing connection
ws = new WebSocket("ws://127.0.0.1:8000");
}
return Service;
The issue arises when the new instance of the web socket does not function as intended.
After researching, I found that the web socket needs to reattach its handlers to the object upon recreation, as discussed in this question.
Moreover, since an AngularJS service is a singleton by nature (as highlighted in this question), I'm left wondering how I can recreate the web socket instance within my AngularJS singleton service.