Search code examples
javascriptangularjsrestangular

How to use data returned by $http request for another request in same controller using angularjs?


I am making a function that makes a http GET request, and then uses part of that response to make another http GET request. However, the data being returned by the first http GET request is wrapped in a lot of unnecessary data (maybe its a promise object), but I just need the json component of it. How do I access the json data of my response in the controller? Here is my code.

 $scope.doSearch = function() {
    var upcResult = Restangular.one('upc',$scope.searchTerm).get()

//the upc returns an item, so i am trying to access that part of the json by using      
  upcResult.item, how if I console.log that it is undefined

$scope.doAnotherSearch = function() {
    var itemResult = Restangular.one('item',upcResult.item).get();

}

Solution

  • You can use promise chain.

    var upcResult = Restangular.one('upc',$scope.searchTerm).get();
    
    upcResult.then(function (result) {
      // call other http get
      return Restangular.one('item',result.item).get();
    }).then(function (result) {
      //....
    });
    

    I don't know if in your case Restangular.one(/*...*/).get(); returns promise but you can wrap it with $q like:

     var upcResult = Restangular.one('upc',$scope.searchTerm).get(); 
     var deferred = $q.defer();
     deferred.resolve(upcResult).then(function(){/*...*/});