在我的angularJS应用程序中,我有一个增加x次的循环。我在循环中使用嵌套的HTTP get请求来获取每次迭代的API响应。
问题是HTTP get函数中的循环计数器没有获得正确的增量值。
// split multiple words
var split = ['stack', 'over'];
// for each word
for(var w = 0; w < split.length; w++) {
// API URL
var api_url = "URL" + split[w]; // correct iteration value, 0, 1, 2, etc...
// get data from API
$http.get(api_url)
// handle successful
.success(function (response) {
console.log(w); // logs 2 everytime! Instead of 0, 1, 2, etc...
});
}
关于如何解决这个问题的任何想法?
答案 0 :(得分:1)
您的$http.get()
是异步的。您的for
循环不会等待异步调用完成。因此,您的for
循环运行完成,启动所有ajax调用,然后稍后您的$http.get()
调用完成并触发.success
处理程序。因此,当完成每个$http.get()
调用时,循环索引在其结束值上。并且,循环索引的结束值为2
。
您可以通过将$http.get()
放入函数并将循环索引传递给该函数来修复它。这个内部函数(通常称为Immediately Invoked Function Express IIFE)为每次调用ajax调用分别跟踪循环索引,因此每个函数都有自己的索引:
// split multiple words
var split = ['stack', 'over'];
// for each word
for (var w = 0; w < split.length; w++) {
(function (i) {
// API URL
var api_url = "URL" + split[i];
// get data from API
$http.get(api_url)
// handle successful
.success(function (response) {
console.log(i); // logs the index that belongs with this ajax call
});
})(w);
}
P.S。我不清楚word_index
是什么,因为你没有定义它?那应该是循环索引吗?
请注意,w
是for
循环中使用的变量。这被传递给新添加的内部函数作为参数,我故意给出了一个不同的名称i
。因此,w
传递给函数,函数参数命名变量i
。
答案 1 :(得分:0)
split[word_index]
应更改为split[w]
答案 2 :(得分:0)
您正在w
处理程序中记录success
的值,即客户端收到服务器响应时。
响应通过网络发送,因此异步接收。
当第一个响应处理时,所有请求都已 已发送 。
如果你需要http响应处理程序中的单词value,那么考虑重构你的API:将单词作为请求参数(而不是作为字符串url的一部分)可能是有意义的,或者将它放在响应对象中。然后,您可以在没有 hacky 捕获的情况下获得该值。
另外,请考虑使用then
代替success
:
$http.get(api_url).then(function(httpResponse) {
// request parameters are in httpResponse.config.params
});