AngularJs : Multiple Calls for $http service

Anes El Gongi

this is my code :

        var updateScreen = function() {
          $http.get("http://localhost:5000").then(function(response){
          $scope.numSerie = response.data.refDetail.Num_Serie;

          $http.get("data/tempsgammes.json").then(function(res){
            $scope.time = res.data[$scope.numSerie].temps;
            console.log($scope.time)
          })

         console.log($scope.time)
       }

The first $http.get("http://localhost:5000") returns a list of details that I use in the rest of the code, what interests us is the variable numSerie.

Depending on the value of numSerie, another $http.get("data/tempsgammes.json") will be executed to extract the time for this numSerie from a JSON file.

The problem is I cannot get access to the $scope.time only in the second call for $http. The first console.log() gave me the desired result, but the second one undefined.

Can anyone help me ?

zameb

Edit: The console.log($scope.time) is being called 2 times. You see the first one is giving the right value and the second one isn't. It is because of the async behaviour of "then". It is not intuitive but the second console.log($scope.time) is being called before the "then" has finished, this is why it shows "undefined".

Edit 2: Try the following to probe the execution order on async operations

 $http.get("data/tempsgammes.json").then(function(response){
   alert('first');       // <--- This will be called first
   .then(function(res){  
      alert('third!');   // <--- This will be called third
 });
 alert('second!');       // <--- This will be called second

Yes, you can use $scope.time anywhere, but if you try to use it bellow of the "then", it will not be defined yet. You can put somewhere in your view {{$scope.time}} and probe that it will be defined outside of the $http.get


If you get undefined is probable that the index of res.data[$scope.numSerie] is out of bounds.

First check if you have some error using the developer tools of your browser. $scope.numSerie seems to be the culprit here, check its value or provide more detail

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related