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
出于某种原因,当代码行deferred.resolve()在委托人中触发回调时,此代码不起作用
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.
当deferred.resolve()在回调内部触发时,有一些原因,那么在constroller上的回调不起作用。
Any ideas?
Thanks!
1 个解决方案
#1
14
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.
如图所示,angular中的promise API是范围的一部分,因此,当调用内部回调时,resolve不在$ apply循环中,并且它不知道函数调用。
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.
要解析此$ scope,应在resolve函数之后立即调用$ apply()。如果在服务中,并且$ scope injectable不可用,则可以注入$ rootScope。
#1
14
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.
如图所示,angular中的promise API是范围的一部分,因此,当调用内部回调时,resolve不在$ apply循环中,并且它不知道函数调用。
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.
要解析此$ scope,应在resolve函数之后立即调用$ apply()。如果在服务中,并且$ scope injectable不可用,则可以注入$ rootScope。