AngularJS : Factory Service Controller $http.get

agusgambina picture agusgambina · Mar 25, 2014 · Viewed 7k times · Source

I am trying to retrieve the "cart" in the following way Factory->Service->Controller. I am making an $http call but it is returning an object. If I debug I can see that the request is made and is retrieving the data (in the network section of the debugger).

angular.module('companyServices', [])
.factory('CompanyFactory', ['$http', function($http){
    return {
        getCart: function(cartId) {
            var promise = $http.get('company/Compare.json', {params: {'wsid': cartId}})
             success(function(data, status, headers, config) {
                return data;
            }).
            error(function(data, status, headers, config) {
                return "error: " + status;
            });
        }
    };
}]);

angular.module('itemsServices', [])
.service('ItemsServices', ['CompanyFactory', function(CompanyFactory){
    var cartId = new Object();
    this.getCartId = function(){
        return cartId;
    };
    this.cartId = function(value){
        cartId = value;
    };
    this.getCart = function(){
      return CompanyFactory.getCart(this.getCartId()).then(function(data){return data});
    };
};

.controller('CompareItemsCtrl', ['$scope', '$location', 'ItemsServices', function($scope, $location, ItemsServices){
  var params = $location.search().wsid;
  ItemsServices.cartId(params);
  console.log('ItemsServices.getCart()');
  console.log(ItemsServices.getCart());
};

Thank you

Answer

thescientist picture thescientist · Mar 25, 2014

Since $http returns a promise, I think you would be better of passing in your success and error functions to getCart()

.controller('CompareItemsCtrl', ['$scope', '$location', 'ItemsServices', function($scope, $location, ItemsServices){
  var params = $location.search().wsid;
  ItemsServices.cartId(params);
  console.log('ItemsServices.getCart()');
  console.log(ItemsServices.getCart());
  ItemsService.getCart().then(function(response){
    console.log('success');
  },function(response){
    console.log('error');
  });
};