0

I am trying to push values from one array to a second array, but every time I output the second array, I am getting an empty '[]' output

$scope.myArray = [];
$http.get("http://127.0.0.1/dbtest/init.php").then(function(response){
    $scope.myData = response.data.records;
    for(var i = 0; i < $scope.myData.length; i++){
        $scope.myArray.push({
            text: $scope.myData[i].id,
            image: $scope.myData[i].url
        });
    }
    console.log($scope.myData); //1st output this one works
});
console.log($scope.myArray); //2nd output shows empty array

enter image description here

UPDATE: enter image description here

This is the result I get from the http request

Community
  • 1
  • 1
user538578964
  • 723
  • 9
  • 25
  • it seems you are getting an empty array from your `http` request. Have you checked if your request actually returns any data? – Jorrex Aug 09 '16 at 07:03
  • @Jorrex: Nope, the array from the GET has nine entries in it. – T.J. Crowder Aug 09 '16 at 07:04
  • 3
    it's empty because it's being called before the data is asynchronously loaded into it- that's why its log shows up before the other array. – Polyov Aug 09 '16 at 07:04
  • My bad, still waking up. Haven't had my coffee yet. – Jorrex Aug 09 '16 at 07:05
  • @Jorrex I have added a picture which shows what the http request returns – user538578964 Aug 09 '16 at 07:06
  • @Polyov I have called it after the data is loaded, right? I dont think I fully understand what you mean – user538578964 Aug 09 '16 at 07:08
  • @user3536523 when you make an AJAX request (like with `.get()`), it takes time for the server to respond to the query. So instead of waiting, JS moves on to the next thing, which happens to be the next `console.log()` statement. This is called asynchronous. Move the `myArray` check into the `.then()` block. The array will be filled like you expected. – Polyov Aug 09 '16 at 07:20
  • @Polyov It works after I moved it to the then() block.. So does this mean, that even in the original code I posted, although it was showing as an empty array, the array was filled? – user538578964 Aug 09 '16 at 07:35
  • @user3536523 yes, it was filled after the request went through. Please read up more on AJAX. That will answer your questions. – Polyov Aug 09 '16 at 07:48
  • @Polyov Thanks a lot for all your help. And yeah, I have to read up on a lot of things. Thanks again – user538578964 Aug 09 '16 at 07:54

0 Answers0