[英]Can't resolve issue related to $http.get in angular js
这是我在角度控制器中注入所有必要依赖项的代码。我只显示了我感到困惑的主要部分。
$scope.ipList=["http://www.google.com",
"http://www.yahoo.com",
"http://hello",
"http://www.facebook.com",
"http://hi",
"http://bye"
];
for(var i=0;i<$scope.ipList.length;i++)
{
console.log(i); //1st console
$http.get($scope.ipList[i])
.then(function(response) {
console.log(i);
});
}
when i am executing this then 1st console is printing right result i.e.
0,1,2,3,4,5 but the 2nd console is printing only 5.
I want to execute $http.get() part every time with loop.So what should i do.
.then(function(response) {
console.log(i);
});
这是异步功能,当它触发时, i
已经增加了。 当函数最终触发时,它会记录当前版本的i
,而不是当该函数立即触发时的情况。
你可以做几件不同的事情来绕过阵列复制。 将http.get包装在函数中并触发它将复制变量值。 例如:
for(var i=0;i<$scope.ipList.length;i++)
{
console.log(i); //1st console
(
function (i) {
$http.get($scope.ipList[i])
.then(function(response) {console.log(i);})
)(i);
//depending on the scenario, I would probably extract this outside of the
//loop so it doesn't create it each time the function fires.
//this really depends on the code inside it though, and what needs
//to operate through closure etc.
}
下面是使用setTimout函数的示例,该函数也将强制异步触发。 https://jsfiddle.net/q0nmph0j/
将变量复制到另一个变量将强制第二个变量在第一个变量也不会更新。
var first = 0
var second = first;
first = 3;
console.log(first);
console.log(second);
输出:
3
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.