【问题标题】:angularJS: window.alert only after method is doneangularJS:window.alert 仅在方法完成后
【发布时间】:2015-02-13 07:09:47
【问题描述】:

在我的控制器中,借助服务,我向用户发送了一些 qr 数据:

    $scope.sendtoList = function () {
        $scope.qrStatus = false;
        angular.forEach($scope.users, function (item) {        
          if (item.Selected){
            inviteService.sendQR(item.Emails.main, $scope.company.Id).then(function(response) {
              $scope.qrStatus = true;              
            },
            function(err) {
              $scope.qrStatus = false;              
            });
          }
        });
        if ($scope.qrStatus){
          $window.alert('QR-code has been sended successfully.');
        }
        else{
          $window.alert('Warning! QR-code has not been sended successfully.');
        }
      }

我看到一些奇怪的行为:它总是显示警告警报,即使方法成功完成 - 我认为这是有希望的。但是只有在服务承诺返回后,我才能在我的情况下显示窗口?

【问题讨论】:

  • 你需要以非阻塞的方式处理这个,而不是阻塞的方式。代码完成后,您的承诺将返回。
  • @BrianNoah 你能提供代码示例吗?
  • 完成。未经测试,但我发布的内容应该可以工作。

标签: javascript angularjs


【解决方案1】:

为了使用 Promise 执行此操作,您需要创建一个计数器,每次更新用户时检查一次,然后在全部计算完毕后触发警报。

$scope.sendQRtoList = function () {
    $scope.qrStatus = false;
    var count = 0;
    var length = $scope.users.length;
    var error = 0;
    angular.forEach($scope.users, function (item) {
        if (item.Selected){
            inviteService
                .sendQR(item.Emails.main, $scope.company.Id)
                .then(function(response) {
                    //yay!  
                },
                function(err) {
                    error++;
                })
                .finally(function () {
                    count++;
                    if (count === length && error === 0) {
                        $window.alert('QR-code has been sent successfully.');
                    }
                    if (count === length && error !== 0) {
                        $window.alert('Warning! QR-code has not been sent successfully.')
                    }
                });
        }
    });
};

.finally() 发生在每个承诺上,这就是您要添加计数器增量的地方。

【讨论】:

    【解决方案2】:

    希望以下其中一项有所帮助

    1) 尝试查看以下帖子:$success call back function from AngularJS

    这是一个类似的问题,下面的 js fiddle 可能会有所帮助:http://jsfiddle.net/E5HGy/6/

    2) 如上所述的计数器也可以解决问题,例如

    if(i == selector.length) 
        // "callback" 
    

    基本上会解决它

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 2021-01-27
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多