0

Hello this is my second time using AngularJS... I create a http request and no problem with it. But the question is, how i can get the result of this request or put in a variable ?

var cust_url = "RETURN A JSON";    
var FINAL_FILE = "";

$http.get(cust_url)
    .then(function (response) {    
        $scope.details = response.data;   
        //--> do multiple modify to response.data      
        FINAL_FILE = 'something';
    }); 

$scope.data = {   
    /*USE HERE --> FINAL_FILE       
    return -> undefined on console if i try to access to FINAL_FILE
    */
};

Like the example... sorry i think is a stupid error. Thanks for your time.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
redOne
  • 25
  • 1
  • 5

2 Answers2

1

$http request is asynchronous, this is the reason that you get the undefined value. If you want to use the response data, you have to do it inside the then callback, where the data are available, like this:

$http.get(cust_url)
    .then(function (response) {

        $scope.details = response.data;

        //--> do multiple modify to response.data  

        FINAL_FILE = 'something';

        // here use the $scope.details or call a function to use data

        $scope.data = { };

});
Bill P
  • 3,622
  • 10
  • 20
  • 32
1

Return data to the .then method and save the promise:

var finalFilePromise = $http.get(cust_url)
.then(function (response) {    
    $scope.details = response.data;   
    //--> do multiple modify to response.data      
    FINAL_FILE = 'something';
    return FINAL_FILE;
});

To use, extract the data from the promise:

$scope.data = {   
    //USE HERE --> FINAL_FILE       
    finalFilePromise.then(function(FINAL_FILE) {
        console.log(FINAL_FILE);
    });        
};

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95