lemoncodes lemoncodes - 4 months ago 24
AngularJS Question

Angular JS $http promises

i just want to ask about $http and promise usage, i seem to have a problem understanding on how to use it properly, i have ready some threads and guides on how to implement, i may have misunderstood it but here is what i did. I keep it as simple as possible in order for me to grasp it.

this.getAll = function(){
var details = [];

var deffered = $q.defer();

var promise = $http.get('../test_data/patient_list.json');

promise.then(function(response){
$log.debug(response.data);
angular.copy(response.data, details);
details = response.data
});

return details;
};


during
promise.then()
data do exists, but when i try to copy it to another array after
promise.then
call
details
is empty. How come? Im a bit confused now, can anyone point or teach me how to properly handle data on
$http

Answer
this.getAll = function(){
var details = [];

var deffered = $q.defer();

var promise = $http.get('../test_data/patient_list.json');

return promise.then(function(response){
    $log.debug(response.data);
    angular.copy(response.data, details);
    details = response.data
    return details; 
});

};

you have to return the promise then return details inside the .then() block.

you can also do the following:

this.getAll = function(){
 return $http.get('../test_data/patient_list.json')
  .then(function (response) {
     return response.data
  });
}