How do I make multiple HTTP requests in my case?

I am trying to use a factory object to make multiple HTTP requests. I have something like

angular.module('App').factory('myFactory', function($http, $q) {
    var service = {};

    service.setProduct = function(productObj) {
        _productObj = productObj;
    }

    service.makeRequest = function() {
        var deferred = $q.defer();

        $http.post('/api/product', _productObj).success(function(data){
            var id = data.id
            //I am not sure how to chain multiple calls by using promise.
            //$http.post('/api/details/, id).success(function(data) {
            //    console.log(data)
            //}
            deferred.resolve(data);
        }).error(function() {
            deferred.reject('error here');
        })
        return deferred.promise;
    }
    return service;
});







angular.module('App').controller('productCtrl', ['$scope','$http','myFactory',
    function($scope, $http, myFactory) {
        myFactory.setProduct(productObj);
        myFactory.makeRequest()
            .then(function(data) {
               console.log(data) 
            }, function(data) {
               alert(data)
            })

    }
]);

      

I was able to use myfactory.makeRequest () to make a single call, but not sure how to chain multiple HTTP requests. Can someone please help me? Thank!

+3


source to share


2 answers


If you need to make sequential requests, you need to create a chain of promises. You don't even need to create your own object deferred

- it $http.post

already returns a promise, so you can just do .then

that.

return $http.get("url1")
   .then(function(response){

     var nextUrl = response.data;
     return $http.get(nextUrl);
   })
   .then(function(response){

     var nextUrl = response.data;
     return $http.get(nextUrl);
   })
   .then(function(response){

     return response.data;
   });

      



.success

used for a more traditional, no-brainer approach

Here's the plunker .

+2


source


Take some readings on promises. Remember JS is in asynchronous mode. You will need to make the next server call in the callback (the first .then function).



0


source







All Articles