【问题标题】:How to use $q to get a promise from a $broastcast in angularJS如何使用 $q 从 angularJS 中的 $broadcast 中获得承诺
【发布时间】:2014-02-10 20:39:32
【问题描述】:

现在我的控制器代码如下所示:

$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({ ... });


});

我希望在处理完广播后打开模态实例。有没有办法做到这一点?

更新:我倒在考虑这个问题。我本来打算在模态实例之后进行广播,无论如何,没关系。

PS:我确实遇到了 modalinstance.opened 回调的问题,但我不得不绕过它。我仍在努力正确使用 $q,我的代码越来越混乱。

【问题讨论】:

  • 你的代码看起来不错,它应该做你想做的事。因为$broadcast()是同步操作,所以$broadcast()返回时应该调用所有的事件处理函数

标签: angularjs promise broadcast q


【解决方案1】:

您的控制器代码看起来不错,应该可以按预期工作,您只是不需要第一个 then() 中的延迟对象:

$scope.spAPI.load(id).then(function(result){

  if(result !== undefined){
    $rootScope.$broadcast("onSpLoaded", result);
  }

}).then(function(success){

  $scope.modalInstance = $modal.open({ ... });


});

这里的原因是因为$broadcast()是同步操作,当$broadcast()返回时,所有的事件处理程序都会被调用;并且第二个then() 中的函数只会在第一个then() 中的函数返回后调用,因此$modal.open() 将在所有事件处理程序之后调用。

DEMO

更新:

您知道$scope.modalInstance.opened 是一个承诺,将在显示模式时解决,因此您可以尝试以下方法来实现您想要的:

$scope.spAPI.load(id).then(function(result){
    $scope.modalInstance = $modal.open({ ... });

    $scope.modalInstance.opened.then(function() {
        $rootScope.$broadcast("onSpLoaded", result));
    });
});

【讨论】:

猜你喜欢
  • 2014-10-31
  • 2016-03-18
  • 2013-09-11
  • 1970-01-01
  • 2016-09-22
  • 2013-05-23
  • 2014-07-06
  • 2016-04-24
  • 2014-06-27
相关资源
最近更新 更多