2

我正在尝试通过以下方式工厂->服务->控制器检索“购物车”。我正在进行 $http 调用,但它正在返回一个对象。如果我调试,我可以看到请求已发出并正在检索数据(在调试器的网络部分中)。

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

谢谢

4

1 回答 1

2

由于 $http 返回一个承诺,我认为你最好将你的成功和错误函数传递给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');
  });
};
于 2014-03-25T03:37:58.753 回答