如何将值传递给 AngularJS $http 然后回调
How to pass a value to an AngularJS $http then callback
我的问题与此处的问题非常相似:
根据Angular.js
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
那么,如何使用 .then 做类似的事情呢?
我的代码在我的服务中有类似这样的碎片
fetchFromAPI: function(key) {
return $http.jsonp(...);
}
这是我的控制器
for (var i = 0; i < units.length; i++){
Service.fetchFromAPI(i)
.then(function(response) {
console.log(i);
}, function(response) {
console.log(response);
});
}
但是控制台的输出是相同的数字,因为在返回任何调用之前 for-loop 完成执行,我无法绕过上面类似于 .success 示例的代码,我所有的尝试都给我一个错误,我的控制器不是一个函数。
Jim Horng 发布的解决方案是
$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));
一个快速的解决方案可能是:
for (var i = 0; i < units.length; i++){
Service.fetchFromAPI(i)
.then((function(key) {
return function (response) {
console.log(key, response);
};
})(i), function(response) {
console.log(response);
});
}
只需使用内置 angular.forEach
angular.forEach(units, function(unit, index){
Service.fetchFromAPI(unit)
.then(function(response) {
console.log(unit, response);
}, function(response) {
console.log(response);
});
}
我的问题与此处的问题非常相似:
根据Angular.js
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
那么,如何使用 .then 做类似的事情呢?
我的代码在我的服务中有类似这样的碎片
fetchFromAPI: function(key) {
return $http.jsonp(...);
}
这是我的控制器
for (var i = 0; i < units.length; i++){
Service.fetchFromAPI(i)
.then(function(response) {
console.log(i);
}, function(response) {
console.log(response);
});
}
但是控制台的输出是相同的数字,因为在返回任何调用之前 for-loop 完成执行,我无法绕过上面类似于 .success 示例的代码,我所有的尝试都给我一个错误,我的控制器不是一个函数。
Jim Horng 发布的解决方案是
$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));
一个快速的解决方案可能是:
for (var i = 0; i < units.length; i++){
Service.fetchFromAPI(i)
.then((function(key) {
return function (response) {
console.log(key, response);
};
})(i), function(response) {
console.log(response);
});
}
只需使用内置 angular.forEach
angular.forEach(units, function(unit, index){
Service.fetchFromAPI(unit)
.then(function(response) {
console.log(unit, response);
}, function(response) {
console.log(response);
});
}