Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js deferred doesnt work in callback

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!

like image 490
Dimkin Avatar asked May 24 '13 10:05

Dimkin


1 Answers

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.

like image 168
Dimkin Avatar answered Nov 02 '22 04:11

Dimkin