gpt4 book ai didi

javascript - AngularJS REST 调用 - 属性 'name' 未定义

转载 作者:行者123 更新时间:2023-11-29 18:16:03 25 4
gpt4 key购买 nike

我正在像这样调用 OpenWeatherMap API:

$scope.cities = [
{name: 'Phoenix,US'},
{name: 'Atlanta,US'},
{name: 'Honolulu,US'}
];

$scope.reload = function() {
$scope.items = [];
for (var i = 0; i < $scope.cities.length; i++) {
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('http://api.openweathermap.org/data/2.5/weather?q=' + $scope.cities[i].name).success(function(data, status, headers, config) {
$scope. items.push(data);
});
}
$scope.name0 = $scope.items[0].name //error occurs here
};

我收到错误“属性‘name’未定义。我不知道为什么会出现此错误,因为‘name’是 OpenWeatherMap API 中的有效 ID。

最佳答案

首先为$http请求创建一个工厂

  myApp.factory('cityData',function($q,$http){
return function(cities){

var promises = cities.map( function(city){
var deffered = $q.defer();

delete $http.defaults.headers.common['X-Requested-With'];

$http({
url : 'http://api.openweathermap.org/data/2.5/weather?q=' + city.name,
method: 'GET'
})
.success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});

return deffered.promise;

});

return $q.all(promises);
}

});

然后在 Controller 中调用它:

 cityData($scope.cities).then(function(datas){
$scope.name0 = datas[0].name;
console.log($scope.name0);
});

查看演示 Here

关于javascript - AngularJS REST 调用 - 属性 'name' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23284935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com