0

Im using web sockets in my AngularJS application.
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.
The web socket is contained within a service (code is simplified a bit):

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;

The problem is that the new instance of the web socket does not work.
According to this question the web socket needs to reattach its handlers to the object when its recreated.
But a AngularJS service is a singleton (and should stay a singleton according to this question).
How can I recreate the web socket instance inside my AngularJS singleton service?

Community
  • 1
  • 1
Vingtoft
  • 13,368
  • 23
  • 86
  • 135

1 Answers1

0

I found the solution myself. It was actually pretty simple:

angular.module('myApp').factory("SubscriptionFactory", function () {
    var Service = {};
    var ws;

    Service.onMessage = function(message) { /* some code */};
    Service.onClose = function() { /* some code */ };
    Service.onOpen = function() { /* some code */};
    Service.onError = function(error) { /* some code */};

    Service.connect = function() {
        // (Re)connect
        ws = new WebSocket("ws://127.0.0.1:8000");
        // Reattaching handlers to object
        ws.onmessage = Service.onMessage;
        ws.onclose = Service.onClose;
        ws.onopen = Service.onOpen;
        ws.onerror = Service.onError;
    }
    return Service;

What happens here is simple: Im creating a new Web Socket object and manually attaching the Web Sockets handlers to my AngularJS service.

Vingtoft
  • 13,368
  • 23
  • 86
  • 135