AngularJS:工厂服务控制器$ http.get

时间:2014-03-25 03:31:47

标签: angularjs angularjs-service angularjs-controller angularjs-factory

我正在尝试以下列方式检索“购物车”:Factory-> Service-> Controller。 我正在进行$ 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());
};

谢谢

1 个答案:

答案 0 :(得分: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');
  });
};