I have an application reading some values from an external device. I'm using angularjs as my javascript framework. I'm using angular-ui for my routing.
I'm using the resolve to pass the web socket it to the controller, since it could be used in multiple screens
.state('dashboard.count', {
parent: 'dashboard',
url: "/lane/:laneID",
templateUrl: '/app/count/count.html',
controller: 'CountCtrl as vm',
resolve: {
websocket: ['webSocketFactory', function (webSocketFactory) {
return webSocketFactory.websocket;
}]
}
});
The websocket is retrieved by a factory:
function webSocketFactory($log, wsUri) {
var factory = {
sendMessage: sendMessage,
websocket: new WebSocket('myurl')
}
return factory;
}
}
In my controller I have a simple calls to the websocket API
websocket.onopen = function () {
$log.debug('open');
webSocketFactory.sendMessage('send my message through the factory');
vm.connecting = false;
}
Probably 70% of the time this works just fine vm.connecting
gets set to false and I can use the web-socket. However, it's unpredictable.
I'm not real happy with the accepted answer on this SO Question, The one voted higher seems to be the pattern I'm following. Does anyone have any suggestions how to make this more predictable?