AngularJS: Reconnect WebSocket Inside A Service
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 bac
Solution 1:
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.
Post a Comment for "AngularJS: Reconnect WebSocket Inside A Service"