javascript - 如何在 AngularJS Controller 中发出同步 AJAX 请求

标签 javascript jquery ajax angularjs angular-promise

有人告诉我 Angular 中的 $http 是异步的。但是,出于某种目的,我需要发出连续的 AJAX 请求。 我想从文件列表中读取所有文件,然后从所有这些文件中获取编号。例如:

“文件名”的内容:

file1
file2

“file1”的内容:

1

“file2”的内容:

2

下面的代码会计算和

<!DOCTYPE html>
<html>
<body>
<p id="id01"></p>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>

var fileString;
/* first AJAX call */
$.ajax({
    url: 'fileNames', type: 'get', async: false,
    success: function(content) {
        fileString = content;
    }
});
var fileList = fileString.split('\n');
var sum = 0;
for (var i = 0; i < fileList.length; i++) {
      /* second AJAX call in getNumber function */
      sum += getNumber(fileList[i]);
}
document.getElementById("id01").innerHTML = sum;

function getNumber(file) {
    var num;
    $.ajax({url: file, type: 'get', async: false,
      success: function(content) {
            num = content;
        }
    });
    return parseInt(num);
}

</script>
</body>
</html>

由于这两个 $.ajax 调用是顺序的,我不知道如何在 AngularJS 中实现此功能。比如说,最后,我想要 $scope.sum = 1 + 2。

有人可以让它在 AngularJS 中工作吗?一些简单的代码将不胜感激!

最佳答案

您可以使用 promise 和 promise 链接(使用 $q$http 返回的 promise )。示例:在您的 Controller 中,您可以这样做(在注入(inject) $http $q 之后):

angular.module('myApp').controller('MyCtrl', ['$http','$q','$scope', function($http, $q, $scope){

    function getData(){
        //return promise from initial call
         return $http.get('fileNames')
                .then(processFile) //once that is done call to process each file
                .then(calculateSum);// return sum calculation
      }

      function processFile(response){
         var fileList = response.data.split('\n');
          //Use $q.all to catch all fulfill array of promises
          return $q.all(fileList.map(function(file){
             return getNumber(file);
          }));
      }

      function getNumber(file) {
          //return promise of the specific file response and converting its value to int
          return $http.get(file).then(function(response){
             return parseInt(response.data, 10);
          });

          //if the call fails may be you want to return 0? then use below
          /* return $http.get(file).then(function(response){
             return parseInt(response.data, 10);
          },function(){ return 0 });*/
      }

      function calculateSum(arrNum){
          return arrNum.reduce(function(n1,n2){
             return n1 + n2;
          });
      }

      getData().then(function(sum){
         $scope.sum = sum;
      }).catch(function(){
         //Oops one of more file load call failed
      });

}]);

另见:

这并不意味着调用是同步的,但它们是异步的,并且仍然以更高效且易于管理的方式执行您需要的操作。

Demo

关于javascript - 如何在 AngularJS Controller 中发出同步 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745116/

相关文章:

javascript - 将 CSS 样式添加到 SVG

javascript - 如何在jquery中获取同一类的文本值

javascript - ajax获取html中选项值的文本

javascript - 如何将批处理文件中写入的dos命令写入javascript

javascript - Bootstrap 4 : Fixing and fading in footer at the bottom of the page

jquery - 使用 Rails 和 JSON 选择2

php - 使用 Ajax 的 HTML 搜索建议不会使用键盘自动完成

javascript - 我如何循环遍历数组并在 jquery 中动态创建项目

javascript - 有没有办法使用浏览器从要求授权 header 的 RESTful Web 服务下载文件

javascript - 是否有正确的方法来 $.extend jQuery 中的嵌套属性?