Reputation: 799
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!
Upvotes: 3
Views: 1082
Reputation: 49590
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.
Upvotes: 2
Reputation: 2569
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).
Upvotes: 0