In angular however there are promise service that implements the promise pattern. Using them can make the asynchronous work easier. For those who are unaware of what promises are there is a documentation available here.
When implementing the promise pattern inside service you probably will have to run the deffered.resolve() command inside the callback as javascript is most of the time asynchronous. The weird thing for me was that it does not work from the callback. The function registered inside .then function will not run!
Consider the following example:
angular.module('myModule', [], function () {
})
.service('dataService', ['$q', '$timeout', function ($q, $timeout) {
this.getData = function () {
var deferred = $q.defer();
$timeout(function () {
someHttpGetter.getData(data);
deferred.resolve(data);
}, 2000);
return deferred.promise;
};
}]);
In this example the callback inside .then function will work correctly. On the other hand, this example:
angular.module('myModule', [], function () {
})
.service('dataService', ['$q', '$timeout', function ($q, $timeout) {
this.getData = function () {
var deferred = $q.defer();
$timeout(function () {
someHttpGetter.getData(function (data) {
deferred.resolve(data);
});
}, 2000);
return deferred.promise;
};
}]);
Here, the deffered.resolve() is inside a callback. It will not work.
The reason for that is that in the first example the resolve will happen inside the digest cycle of angular, while in the second example the resolve happens in callback, thus, outside the cycle.
The solution for this (as I found) is to inject the rootScope to the service and invoke the $rootScope.$apply() right after the resolve method. The complete working example should look like this:
angular.module('myModule', [], function () {
})
.service('dataService', ['$rootScope', '$q', '$timeout', function ($rootScope, $q, $timeout) {
this.getData = function () {
var deferred = $q.defer();
$timeout(function () {
someHttpGetter.getData(function (data) {
deferred.resolve(data);
$rootScope.$apply();
});
}, 2000);
return deferred.promise;
};
}]);