use $http.get in a service/factory to return a collection

Serge picture Serge · Oct 30, 2015 · Viewed 12.6k times · Source

I try to use a http.get promise in an angularjs service, do some manipulation on the obtained collection and finally return it to a controller...

My question is how to use a $http.get() in a service in order to obtain and manipulate the result before returning it to the controller, like in the code bellow : The PEN code

Answer

Pankaj Parkar picture Pankaj Parkar · Oct 30, 2015

Basically you could modified the data inside the ajax success call & then return that data from the success. But for returning data from ajax success you need to use promise pattern to return out data from $http.get. you need to return the object from the $http.get promise, & inside .then function of $http.get you could manipulate data.

Factory

app.factory('customer', ['$http', function($http) {
    var all, odds = [];
    var getData = function() {
        return $http.get("http://www.w3schools.com/angular/customers.php")
        .then(function(response) {
          all = response.records;
          angular.forEach(all, function(c, i) {
            if (i % 2 == 1) {
              odds.push(c);
            }
          });
          return odds
        });
    }
    return {
        getData: getData 
    };
}]);

Controller

app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
    customer.getData().then(function(response){
         $scope.odds = response;
    });
}]);