Created
February 22, 2017 02:08
-
-
Save theshane/b7cf244f9149404221670806305e65f3 to your computer and use it in GitHub Desktop.
ANGULAR WEBSOCKET FACTORY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
angular | |
.module('serviceRequest') | |
.factory('webSocket', webSocket); | |
/* @ngInject */ | |
function webSocket($rootScope,$timeout) { | |
var socket; | |
var messages = {}; | |
connect(); | |
var service = { | |
socket: getSocket, | |
messages: messages | |
}; | |
return service; | |
//////////////// | |
function getSocket(){ | |
return socket; | |
} | |
function connect() { | |
try { | |
var host = "ws://localhost:8000/websocket"; | |
socket = new WebSocket(host); | |
console.log('Socket Status: ' + socket.readyState); | |
socket.onopen = function() { | |
console.log('Socket Status: ' + socket.readyState + ' (open)'); | |
} | |
socket.onmessage = function(msg) { | |
//Convert to json | |
var data = JSON.parse(msg.data); | |
//Create the attribute | |
if (!messages[data.notification_from]) { | |
messages[data.notification_from] = []; | |
} | |
//Populate an array (Note sure if I need this) | |
messages[data.notification_from].push(data.response); | |
//Broadcast the tag of the helper with the response. | |
//EX: $rootScope.$broadcast('get_issue', data.response); | |
//Now my controllers/factories can do $on('get_issue',...) | |
//Timeout ensures this is done after everything is loaded. | |
$timeout(function() { | |
$rootScope.$broadcast(data.notification_from, data.response); | |
}); | |
} | |
socket.onclose = function() { | |
setTimeout(function() { | |
console.log('Socket Status: ' + socket.readyState); | |
if (socket.readyState != 1) { | |
connect(); | |
} | |
}, 3000); | |
console.log('Socket Status: ' + socket.readyState + ' (Closed)'); | |
} | |
} catch (exception) { | |
console.log('Error' + exception); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment