Lalit Kushwah
Lalit Kushwah

Reputation: 4049

Can't resolve issue related to $http.get in angular js

Here is the code i have inject all the necessary dependencies in angular controller.I have shown only main part on which i am confuse.

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

Upvotes: 1

Views: 51

Answers (1)

kemiller2002
kemiller2002

Reputation: 115488

.then(function(response) {
                     console.log(i);
                 });

This is async function, by the time it fires, i has already incremented. When the function eventually fires, it logs the current version of i, not what it would be if it that function were to fire immediately.

You can do a couple of different things to get around the array copying. wrapping the http.get in a function and firing it will copy the variable values. For example:

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. 

        }

Here is an example using the setTimout function, which will force firing asynchronously too. https://jsfiddle.net/q0nmph0j/

Copying a variable to another variable will force the second variable to not update once the first has too.

var first = 0
var second = first; 

first = 3;

console.log(first);
console.log(second);

Output:

3
0

https://jsfiddle.net/qf776j3e/

Upvotes: 3

Related Questions