1

I currently have a factory that submits a POST request with data.

Here is the factory:

app.factory('Quotes', ['$http',function($http, $q) {

  var urlBase = 'http://test-url.com';
  var Quotes = {};

  Quotes.createQuote = function (data) {
    return $http.post(urlBase + '/', data)
  };

  return Quotes;
}]);

I have an array of objects, and each object needs to be submitted separately in it's own POST request. I have this controller..

I am passing $scope.array into the saveQuote() function.

$scope.saveQuote = function(data){
    $rootScope.loading = true;

    angular.forEach(data, function(quote){

      Quotes.createQuote(quote)
        .success(function (data, status, headers, config) {
            $rootScope.loading = false;
            $rootScope.status = {header: "Success", message: "Success", type: "success"};
        })
        .error(function (data, status, headers, config) {
            $rootScope.status = {header: "Error", message: data};
        });         
    });
}  

How do i create a function when ALL of the post requests have completed?

UPDATE:

Also, how do i output each error response for each POST? It seems the answer below outputs only one of them?

Matt Price
  • 1,371
  • 2
  • 9
  • 19

1 Answers1

3

use the $q service

$scope.saveQuote = function(data){
    $rootScope.loading = true;
    var createdQuotes = [];

    angular.forEach(data, function(quote){
      createdQuotes.push(Quotes.createQuote(quote));         
    });

    $q.all(createdQuotes).then(function() {
       //do something now that all the quotes are created

       $rootScope.loading = false;
       $rootScope.status = {header: "Success", message: "Success", type: "success"};
    }, function(data) {
       $rootScope.status = {header: "Error", message: data};
    });
}

Quote.createQuote will have to return the promise though to make this work.

And better yet, you can change the forEach to map to reduce the first part to one line like this:

var createdQuotes = data.map(Quotes.createQuote);
DerekMT12
  • 1,329
  • 11
  • 15
  • Thank you for this. This works. However, it only seems to be capturing the error response for one of the calls. How would i collate and display the error response for each call, as the 2 submissions could contain different errors. – Matt Price Feb 05 '16 at 08:14
  • After the first error, `$q.all` doesn't care about the rest of the requests and immediately calls its error handler. To handle each error, you could keep your original `forEach`, and add an error handler for each call when you push it onto `createdQuotes`. If you're wanting to wait on all of the responses to come back, error or not, you might could use the library referenced in this answer: http://stackoverflow.com/a/32008390/1636157 – DerekMT12 Feb 05 '16 at 14:36