I'm working on an angularJS app and this is my first website using this framework. In my app i've a need to make a $http call inside a for loop. With in the loop before the next iteration I want to wait for the response from my previous call. What is the best and simple way to do this. I've tried using the callBack, $q.all(), .then in all of these only the last request is going through. Please help.
Note: My API that i'm calling through $http can't queue requests.
Edit: I've tried both the below approaches, in both of the cases only the last request is being made successfully. Can you tell me what is wrong i'm doing here.
Approach 1:
var promiseArray=[];
for(var i=0;i<items.length;i++)
{
var promise=services.Post(items[i]);
promiseArray.push(promise);
}
$q.all(promiseArray).then(data)
{
...
}
Approach 2:
var promises = [];
for (var i = 0; i < items.length; i++) {
var deffered = $q.defer();
var promise = services.Post(items[i]);
promise.success(function(data) {
deffered.resolve(data);
})
promises.push(deffered);
}
var result = $q.all(promises);
EDIT :2 Service Code:
Services.Post = function(lineItemId, submitUrl) {
var url = (submitUrl) ? submitUrl : Services.serviceUrl;
return $http.post(url, {
"LineItemID": lineItemId
}).
success(function(data, status, headers, config) {
Services.processResponse(data, status, headers, config);
}).
error(function(data, status, headers, config) {
JL('Angular').error('Error response when calling Service ' + config);
});
};