有人告诉我 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
});
}]);
另见:
- $http
- $q
- $q.all
- Array.map - 您也可以手动遍历数组并将 promise 推送到数组。
- Array.reduce - 您也可以遍历数字并将它们相加。
这并不意味着调用是同步的,但它们是异步的,并且仍然以更高效且易于管理的方式执行您需要的操作。
关于javascript - 如何在 AngularJS Controller 中发出同步 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745116/