Consider the following example:
.service('movieGetter', ['$q', '$timeout', function ($q, $timeout) {
this.getData = function () {
var deferred = $q.defer();
$timeout(function(){
mock.getData(function(data){
deferred.resolve(data);
});
}, 2000);
return deferred.promise;
};
}]);
For some reason this code doesn't work, when the line deferred.resolve() fires the callback at then in the constroller does't
On the other hand tthis example works fine:
.service('movieGetter', ['$q', '$timeout', function ($q, $timeout) {
this.getData = function () {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('test');
}, 2000);
return deferred.promise;
};
}]);
Fow some reason when the deferred.resolve() fires inside callback the then callback on the constroller doesn't work.
Any ideas?
Thanks!
As it appears, the promise API in angular is part of the scope and thus, when calling resolve inside callback angular is not in the $apply cycle and it's unaware of the function call.
To resolve this $scope.$apply() should be called right after the resolve function. If in service, and the $scope injectable is unavailable you can inject $rootScope instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With