我似乎无法在product
函数中正确设置getProduct()
变量...
如果我在console.log(product)
之后立即angular.copy(products.data[i], product);
,则会正确设置,但我无法弄清楚为什么第3行上的var product = {};
仍为空对象。
任何想法会发生什么?
angular.module('APP').factory('productFactory', function($q, $http) {
var products = [];
var product = {};
var getAllProducts = function(){
return $http.get('./data/product.json')
.then(function(response) {
angular.copy(response, products);
var deferred = $q.defer();
deferred.resolve(response);
return deferred.promise;
});
};
var getProduct = function(id) {
getAllProducts()
.then(function(){
for (var i = products.data.length - 1; i >= 0; i--) {
if(products.data[i].id == id){
angular.copy(products.data[i], product);
}
};
})
};
return {
getAllProducts: getAllProducts,
getProduct: getProduct,
products: products,
product: product
};
})