如何使用$ Q摆脱在angularJS一个$ broastcast一个承诺 [英] How to use $q to get a promise from a $broastcast in angularJS
问题描述
现在我的控制器code是这样的:
Right now my controller code looks like this:
$scope.spAPI.load(id).then(function(result){
var deferred = $q.defer();
if(result !== undefined){
deferred.resolve($rootScope.$broadcast("onSpLoaded", result));
}
return deferred.promise;
}).then(function(success){
$scope.modalInstance = $modal.open({ ... });
});
我想追广播节目进行处理,以开放的模式实例。有没有办法做到这一点?
I want the modal instance to be opened AFTER the broadcasts are processed. Is there a way to do this?
更新:我想这个问题倒退。我的意思是模态实例后做广播,反正不要介意。
Update: I was thinking about this problem backwards. I meant to do the broadcast after the modal instance, anyway, nevermind.
PS:我确实有与modalinstance.opened回调的问题,虽然,我不得不砍围绕自己的路。我仍在苦苦正确使用$ Q,我code已经越来越混乱。
PS: I did have problems with the modalinstance.opened callback though, I had to hack my way around it. I am still struggling to use $q correctly, my code has been getting messier.
推荐答案
您控制器code看起来不错,应该按预期工作,你就不需要延迟对象在第一个则()
:
Your controller code looks fine, it should work as expected, you just don't need the deferred object in your first then()
:
$scope.spAPI.load(id).then(function(result){
if(result !== undefined){
$rootScope.$broadcast("onSpLoaded", result);
}
}).then(function(success){
$scope.modalInstance = $modal.open({ ... });
});
在这里的原因是因为 $广播()
是同步操作,所有的事件处理程序将被调用时 $广播()
的回报;并在第二功能则()
只会在函数后,被称为第一个则()
的回报,所以 $ modal.open()
将所有事件处理程序后调用。
The reason here is because $broadcast()
is synchronous operation, all the event handlers will have been called when $broadcast()
returns; and the function in 2nd then()
will only be called after the function in the first then()
returns, so $modal.open()
will be called after all event handlers.
<大骨节病> 演示 骨节病>
您知道 $ scope.modalInstance.opened
是当模式被所示,将得到解决,所以你可以尝试以下操作来实现你想要的承诺:
You know that $scope.modalInstance.opened
is a promise which will be resolved when the modal gets shown, so you can try the following to achieve what you want:
$scope.spAPI.load(id).then(function(result){
$scope.modalInstance = $modal.open({ ... });
$scope.modalInstance.opened.then(function() {
$rootScope.$broadcast("onSpLoaded", result));
});
});
这篇关于如何使用$ Q摆脱在angularJS一个$ broastcast一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!