AngularJS: assign $ http.get variables to a variable

I am trying to assign data from a $ http.get variable to a variable in my controller.

 $http.get(URL).success(function (data) {
      $scope.results = data;
      console.log('results in $http.get :'+ $scope.results);
    });

 console.log('results after http.get'+ $scope.results);

      

The first console log prints data from get. After $ http.get (url) .success, $ scope.results prints as undefined.

+3


source to share


2 answers


This is because it $http.get

is asynchronous. This way your code won't hold until the ajax request is made, instead it will execute the rest of the code. This way your second console.log

will be executed before the ajax request completes. At the moment, there is no scope variable $scope.results

that is only determined after the request completes, so it prints undefined

. Your first one console.log

will only be printed after the $http

ajax execution completes successfully, at the moment you have the $scope.results

assigned data

one coming from the backend.



+8


source


$http

is a function asynchronous

. It returns instantly, but returns promise

no real result. When the request is complete, it is called onsuccess

.



The second (one outside the call) console.log

is executed before returning $http

.

+2


source







All Articles