I need a global application wise web-socket, which can be used by all of my controller in app.
The following code describes the my use-case where I am creating a factory to share a singleton websocket object. The interface provided are allows the controllers to send the data over socket and attach listener for incoming messages.
The problem with the following code is that I am able to send the data on socket as expected, but not able to receive data when it comes over the socket.
I have read several angular digest related solutions, but they are not working for me.
angular
.module('myApp', [])
.factory('socket', function() {
var socketStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
var socket = new WebSocket("ws://localhost:7070/ws");
socket.onopen = function(event) {
socket.send("hello");
};
socket.addEventListener('message', function(event) {
// I am able to see this so, it is confirmed that server is sending the data
console.log(event);
});
return {
emit: function (data) {
socket.send(JSON.stringify(data));
},
on: function(callback) {
socket.addEventListener('message', callback);
},
getStatus: function() {
var status = socket.readyState;
return socketStates[status]
}
};
})
.controller('MyController', function(socket){
var myctl = this;
//This works
socket.emit({type : "register", name: producer});
//This doesn't work
socket.on(function(event) {
console.log(event);
});
});
$rootScope.$apply(socket.addEventListener('message', callback));
instead of
socket.addEventListener('message', callback);
throws the following error
vendor.js:5 Error: [$rootScope:inprog] $digest already in progress(…)(anonymous function)