Angular.js delayed not working 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 does not work when the line offferred.resolve () starts the callback, and then in the constructor does't

On the other hand, this example works just fine:

  .service('movieGetter', ['$q', '$timeout', function ($q, $timeout) { this.getData = function () { var deferred = $q.defer(); $timeout(function () { deferred.resolve('test'); }, 2000); return deferred.promise; }; }]); 

Determine the reason why the deferred .resolve () function fires inside the callback, then the callback on the constructor does not work.

Any ideas?

Thanks!

+6
source share
1 answer

It appears that the promise API in angular is part of the scope and therefore, when calling permission inside the callback, angular is not in the $ apply loop and it does not know about the function call.

To eliminate this area of ​​$. $ apply () should be called immediately after the permission function. If $ scope is not available in the service and is not accessible for injection, you can instead enter $ rootScope.

+14
source

Source: https://habr.com/ru/post/945764/


All Articles