简体   繁体   中英

How to make multiple http requests in my case?

I am trying to user 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 one call but not sure how to chain multiple http requests. Can someone please help me? Thanks!

If you need to make sequential requests, then you need to chain promises. You don't even need to create your own deferred object - $http.post already returns a promise, so you could just .then it.

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 is used for a more traditional non-promise approach

Here's a plunker .

Do some reading on promises. Remember that JS in asynchronous. You will need to make your next server call within the callback (the first .then function).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM