json - Use response from one $http in another $http in Angularjs -


first of want use $http in order receive data (e.g. students), want make $http call e.g. studentdetails. after want append part of studentdetails students json. need response first call in order create url second call.

problem cannot access response of first http call inside another. know how can done?

var getstudents = function(){    var deferred = $q.defer();    $http.get("https://some_url")    .success(function(response){       deferred.resolve(response);    }).error(function(errmsg){       deferred.reject(errmsg);    });    return deferred.promise; } var appendstudentdetails = function(){   getstudents().then(function(response){      var studentswithdetails = response;      for(var i=0; i<studentswithdetails.length; i++){         $http.get("some_url/"+studentwithdetails[i].user.details+"/")            .success(function(res){               //here want append details,               //received second http call, each student               //of array received first http call                //problem: cannot access response of              //first http call inside            })      }   }) 

you're using deferred anti-pattern deprecated success/error-callbacks. should instead use then, since returns promise, , can chain promises.

here's example of how it:

function getstudents(){     return $http.get('[someurl]'); } function appendstudentdetails(studentswithdetails){     for(var i=0; i<studentswithdetails.length; i++){         appendsinglestudentdetails(studentswithdetails[i]);     } } function appendsinglestudentdetails(singlestudent){     $http.get("some_url/"+singlestudent.user.details+"/")         .then(function(res){             // append stuff             singlestudent.stuff = res.data;         }); }  // call this: getstudents()     .then(function(response){ return response.data; })     .then(appendstudentdetails); 

i decided structure appendstudentdetails function little differently, based on name, call getstudents() within method did before.

beware not use i-variable inside inner then-function, cause troubles closure.

edit: fixed example avoid problem i being under closure.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -