由于AJAX的异步特性,我以前遇到过变量未定义的问题。我已经解决了这个问题,但现在我有了一个新问题。我有以下代码:
$scope.cities = [
{name: 'Phoenix,US'},
{name: 'Atlanta,US'},
{name: 'Honolulu,US'}
];
$scope.items = [];
$scope.reload = function() {
alert("Reload clicked");
var promises = [];
angular.forEach($scope.cities, function(city) {
var deferred = $q.defer();
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city.name).success(function(data, status, headers, config) {
alert("success");
deferred.resolve(data);
});
promises.push(deferred.promise);
});
return $q.all(promises);
};
//not being called after reload button is clicked
$scope.reload().then(function(data) {
$scope.name0 = data[0].name;
alert($scope.name0);
);
我的$scope.reload
会在初始页面加载以及单击我的重新加载按钮时被调用。但是,点击我的重新加载按钮后,scope.reload().then(function(data))
不会被调用;它只会在初始页面加载时被调用,即使$scope.reload
被调用(使用我的警报语句进行测试)。
有谁能告诉我这里我做错了什么?
答案 0 :(得分:1)
您必须将then()
函数放在reload()
函数中。
工作小提琴
我创建了a working fiddle给你看。
我移动了这段代码:
$q.all(promises).then(function(data) {
$scope.answer = data;
});
并将其放入reload
功能。
$scope.reload = function () {
var promises = [];
angular.forEach($scope.cities, function (city) {
var deferred = $q.defer();
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city.name).success(function (data, status, headers, config) {
deferred.resolve(data);
});
promises.push(deferred.promise);
});
// This block here:
$q.all(promises).then(function(data) {
$scope.answer = data;
});
};
答案 1 :(得分:0)
不确定它是否会产生影响,但您并不需要在循环内手动创建新的承诺。 $ http已经返回了您可以使用的承诺:
var promises = [];
angular.forEach($scope.cities, function(city) {
delete $http.defaults.headers.common['X-Requested-With'];
var promise = $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city.name);
promise.success(function(data, status, headers, config) {
alert("success");
});
promises.push(promise);
});