angular-signalr-hub
angular-signalr-hub copied to clipboard
Question: how to handle promise
I'm struggling with the factory and the async nature of it as a AngularJS newbie, unfortunately the provided chat app does not handle my problem:
MetronicApp.factory('Meter', [
'$rootScope', 'Hub', function ($rootScope, Hub) {
var hub = new Hub('meterHub', {
listeners: {
'SendCurrentActuals': function (message) {
$rootScope.$broadcast('SendDataEvent', message);
}
},
methods: ['GetCurrentActuals'],
errorHandler: function (error) {
console.error(error);
},
hubDisconnected: function () {
if (hub.connection.lastError) {
hub.connection.start();
}
}
});
var getCurrentActuals = function () {
return hub.GetCurrentActuals();
};
return {
getNumbers: getCurrentActuals
};
}]);
MetronicApp.controller('DashboardController', function ($rootScope, $scope, Meter) {
console.log(Meter.getNumbers());
});
Gives Error: SignalR: Connection must be started before data can be sent. Call .start() before .send(). I'm struggling how to incorporate the hub.promise.done in the code above to execute only when the hub has connected. I tried several approaches with no luck..
Thanks!
There are multiple ways of getting this to work. A very quick and dirty way is just putting a timeout around your console.log.
Like this (adjust the 1000 to whatever works):
$timeout(function () {
console.log(Meter.getNumbers());
}, 1000);
But as I stated, that is just quick and dirty.
Another possibility is adding a variable to your factory as an indicator if the hub is ready. Make this a boolean eg
var hubReady = false;
In the hub.promise.done you set this variable to true. And in your function getCurrentActuals you first check for the value of hubReady. If the hub is not ready, you handle that gracefully. If it's ready, you call the hub method.
If you expose the hubReady variable to the controller, you could add a watch on the variable. So that as soon as the hubReady variable changes to true, your console.log will fire.
You could also do a broadcast in the hub.promise.done and catch that broadcast in your controller.
Great thanks! I'll try this, maybe worth to add this to the samples :)