title: AngularJS: Reconnect WebSocket inside a service
body: <p>Im using web sockets in my AngularJS application.<br />
  When a user logs out the web socket connection is closed by the client. 
  I need to reconnect the web socket when the user logs back on. <br/>
  The web socket is contained within a service (code is simplified a bit):</p>
  
  <pre><code>angular.module('myApp').factory("SubscriptionFactory", function () {
      var Service = {};
      var ws = new WebSocket("ws://127.0.0.1:8000");
  
      /* WS methods (onopen, onmessage ect) left out for simplicity */
  
      Service.reestablishConnection = function() {
          // Reestablishing connection
          ws = new WebSocket("ws://127.0.0.1:8000");
      }
      return Service;
  </code></pre>
  
  <p>The problem is that the new instance of the web socket does not work.<br /> 
  According to <a href="https://stackoverflow.com/questions/13797262/how-to-reconnect-to-websocket-after-close-connection">this question</a> the web socket needs to reattach its handlers to the object when its recreated. <br />
  But a AngularJS service is a singleton (and should stay a singleton according to <a href="https://stackoverflow.com/questions/16626075/non-singleton-services-in-angular">this question</a>).<br />
  How can I recreate the web socket instance inside my AngularJS singleton service? </p>