2

我試圖通過以下方式檢索「購物車」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

所以有什麼問題呢?你會得到一個迴應,它有什麼問題?fwiw,我想你會想成功和錯誤處理程序傳遞給getCart。 'getCart()。then(successFunction,errorFunction)' – thescientist

回答

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