AngularJS承诺链 [英] AngularJS promise chain
问题描述
我有我的应用程序应该打开一个弹出的用户请确认,然后做出一个Ajax CAL和关闭弹出。结果
我试图用链做的诺的(我已经用它,我记得它应该以这种方式工作),但似乎在调用后,阻止 reservationService.confirm($ scope.object);
。现在,它是实现了一个假的服务的setTimeout
和 $ Q
只返回一个承诺(在未来它将使Ajax调用)。这是一个有效的code或没undestood承诺是如何工作的?结果
对于我选择AngularUI并在弹出的code是这样的:
I have my application that should open a popup ask a confirmation at the user, then make an ajax cal and close the popup.
I tried to do it using a chain of promise (I've already used it, and I remember that it should work in this way), but it seems to block after the call toreservationService.confirm($scope.object);
. Now it is a fake service implemented with a setTimeout
and $q
just to return a promise (in future it will make the ajax call). Is this a valid code or I didn't undestood how promise works?
For the popup I choose AngularUI and the code is this:
reservationService.book($scope.object, day)
.then(function(){
var dialogOpts = {/* dialog options omitted*/}
return $dialog.dialog(dialogOpts).open();
})
.then(function(result){
console.log('confirmed? ', result);
if (result){
//After this line it doesn't do nothing, also if the promise is resolved
return reservationService.confirm($scope.object);
}
})
.then(function(){
//this function is never executed
$scope.$emit('object:detail',{object: $scope.object});
});
reservationService:
reservationService:
function confirm(){
var deferred = $q.defer();
setTimeout(function(){
console.log('Confirming');
deferred.resolve(true)
}, 500);
return deferred.promise;
}
解决
变化的setTimeout
与 $超时
角度的服务。
推荐答案
用于 $超时
而不是的setTimeout
导致它的工作原理togheter的角度范围,迫使消化
阶段(或使用 $ scope.apply()
里面的的setTimeout
)。
Used $timeout
instead of setTimeout
'cause it works togheter at the angular scope, forcing the digest
phase (or use $scope.apply()
inside the setTimeout
).
这篇关于AngularJS承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!