gpt4 book ai didi

javascript - 如何将值传递给 AngularJS $http 然后回调

转载 作者:搜寻专家 更新时间:2023-11-01 05:30:14 25 4
gpt4 key购买 nike

我的问题与此处的问题非常相似:How to pass a value to an AngularJS $http success 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(...);
}

这是我的 Controller

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 示例的代码,我所有的尝试给我一个错误,我的 Controller 不是一个函数。

Jim Horng 发布的解决方案是

$http.get('/plugin/' + key + '/js').success((function(key) {
return function(data) {
console.log(key, data);
}
})(key));

最佳答案

只需使用内置的 angular.forEach

angular.forEach(units, function(unit, index){
Service.fetchFromAPI(unit)
.then(function(response) {
console.log(unit, response);
}, function(response) {
console.log(response);
});
}

Docs

关于javascript - 如何将值传递给 AngularJS $http 然后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32179332/

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