你好,我有很多城市
var cityArr = ["London", "Beijing", "Paris", "New York", "Seoul", "HongKong"];我想遍历每个城市,并使用AngularJS和Javascript获得一个JSON,下面是我的代码:
for (i=0; i<cityArr.length; i++){
$scope.$watch('fondCity', function () {
cityService.city = $scope.foundCity;
});
var newUrl = "http://api.waqi.info/feed/" + cityArr[i] + "/?token=5336bd836b9ec064f6c6fe0bf7e2781838c15c87";
$http({
method: "GET",
url: newUrl
}).then(function mySucces(response) {
$scope.newData = response.data;
}, function myError(response) {
$scope.newData = response.statusText;
});
}如何将每个JSON文件添加到一个数组中。
JSON单文件
{
"status": "ok",
"data": {
"aqi": 49,
"idx": 5724,
"attributions": [
{
"url": "http://uk-air.defra.gov.uk/",
"name": "UK-AIR, air quality information resource - Defra, UK"
},
{
"url": "http://londonair.org.uk/",
"name": "London Air Quality Network - Environmental Research Group, King's College London"
}
],
"city": {
"geo": [
51.5073509,
-0.1277583
],
"name": "London",
"url": "http://aqicn.org/city/london/"
}
} 我想让它看起来像这个:
{
"status": "ok",
"data": {
"aqi": 49,
"idx": 5724,
"attributions": [
{
"url": "http://uk-air.defra.gov.uk/",
"name": "UK-AIR, air quality information resource - Defra, UK"
},
{
"url": "http://londonair.org.uk/",
"name": "London Air Quality Network - Environmental Research Group, King's College London"
}
"status": "ok",
"data": {
"aqi": 155,
"idx": 1451,
"attributions": [
{
"url": "http://www.bjmemc.com.cn/",
"name": "Beijing Environmental Protection Monitoring Center (北京市环境保护监测中心)"
},
{
"url": "http://beijing.usembassy-china.org.cn/070109air.html",
"name": "U.S Embassy Beijing Air Quality Monitor (美国驻北京大使馆空气质量监测)"
}
],
{
"status": "ok",
"data": {
"aqi": 28,
"idx": 5722,
"attributions": [
{
"url": "http://www.airparif.asso.fr/",
"name": "AirParif - Association de surveillance de la qualité de l'air en Île-de-France"
}
],发布于 2017-05-21 22:30:10
由于每个响应共享相同的属性,所以您可以实现的最好是拥有每个响应的数组。
var promises = cityArr.map(function(name) {
return $http.get("http://api.waqi.info/feed/" + name + "/?token=5336bd836b9ec064f6c6fe0bf7e2781838c15c87");
}); // For each City Name, create an array filled with Promises.
// Wait for all the Promises to be completed.
$q.all(promises).then(function(data) {
// Create an array of the data attribute from each response.
var results = data.map(function(result) {
return result.data;
});
console.log(results);
});您需要将$q作为依赖项添加到控制器或组件中。
我创建了一个JSBin示例:http://jsbin.com/gukusot/edit?js,console
https://stackoverflow.com/questions/44102274
复制相似问题