无法在角度js中解决与$ http.get相关的问题

时间:2016-03-18 16:18:58

标签: javascript angularjs

这是我在角度控制器中注入所有必要依赖项的代码。我只显示了我感到困惑的主要部分。

$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.

1 个答案:

答案 0 :(得分:3)

.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

https://jsfiddle.net/qf776j3e/