Matt Price
Matt Price

Reputation: 1401

Function when several http methods have completed in Angular factory

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?

Upvotes: 1

Views: 33

Answers (1)

DerekMT12
DerekMT12

Reputation: 1349

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);

Upvotes: 3

Related Questions