在AngularJS服务的现有产品列表中添加新产品时出错

时间:2015-06-24 14:23:10

标签: angularjs

我有一个从数据库中提取产品的服务(只有一次),并且能够将新产品添加到数据库中。

sampleApp.factory('ProductService', function($http) {

var promise;
var ProductService =  {};

ProductService.GetProducts = function() {
    var req = {
        method: 'POST',
        url: ProductURL,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        //data: "action=GET"
    };
    if ( !promise ) {
            promise = $http(req).then(function (response) {
            console.log(response);
            return response.data;
        });
    }
    return promise;
}

ProductService.AddNewProduct = function(NewProduct)  {

    var ProductData = {};
    ProductData = NewProduct;
    ProductData = JSON.stringify(ProductData);
    alert (ProductData);
    promise.push(NewProduct)    // this line giving error

    var req = {
        url: "cgi-bin/AddNewProduct.pl",
        method: 'GET',
        params: {ProductID: NewProduct.ProductID, ProductName: NewProduct.ProductName, ProductImagePath: NewProduct.ProductImagePath, BrandID: NewProduct.BrandID, SubCategoryID: NewProduct.SubCategoryID}
        //params: { NewProduct: ProductData }
    };

    $http(req).success(function()
    {
        alert ('New Product Added!');
    })
    .error(function()
    {
        alert ('New Product Add Error!');
    });
}

return ProductService;
});

在数据库中添加新产品时,我希望此新产品也可以添加到现有产品列表中。

但这一行给了我一个错误:

promise.push(NewProduct)    // this line giving error

TypeError:promise.push不是函数

如何解决此错误?有没有更好的方法来实现同样的目标。

1 个答案:

答案 0 :(得分:1)

专注于这段代码:

if ( !promise )
{
   promise = $http(req).then(function (response) {
     console.log(response);
     return response.data;
   });
}
return promise;

首先,你需要意识到$http(req).then(...)将返回一个promise,而第一个then内的返回值将被传递给promises链中的下一个函数。您需要做的是将$http调用的结果分配给您服务的某个内部变量:

if ( !productList )
{
   return $http(req).then(function (response) {
     productList = response.data
     return response.data;
   });
}
else 
{
   return productList;
}

现在这仍有问题,因为它会在一个实例中返回一个promise,而在另一个实例中返回一个数组,所以你需要让它总是返回一个promise:

sampleApp.factory('ProductService', function($http, $q) {

  ...


if ( !productList )
{
   return $http(req).then(function (response) {
     productList = response.data
     return response.data;
   });
}
else 
{
   var deferred = $q.defer();
   deferred.resolve(productList);
   return deferred.promise;
}

然后,您应该更改AddNew方法以添加到productList变量。请先检查它是否是阵列。

注1:

使用POST检索产品列表并使用GET添加新产品有点奇怪(不应该反过来这样做吗?)

注2

Angular有一种使用$cacheFactory缓存请求的机制,如果您不想使用cacheFactory,还有一些其他库可用,例如:https://github.com/jmdobry/angular-cache