我从ng-model获取数据来自html-> controllers-> services->工厂 保存后我得到了回复就像这样
这是我的回复
Resource {_id: "56fe5ddc414e823023576508", productcode: "101", productname:"desktops",
__v: 0, isDeleted: false…}
$promise:undefined
$resolved:true
__v:0
_id:"56fe5ddc414e823023576508"
isDeleted:false
productcode:"101"
productitems:Array[1]
productname:"desktops"
__proto__:Object
myFacory代码:
factmodule.factory("DashboardItemFactory",function($resource){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id",
{"id": "@id","productid":"@productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
console.log("Data Saved...")
},function(respdata){
console.log("Error while saving the data");
});
},
}
})
请帮助我如何使数据成为承诺..
答案 0 :(得分:0)
您需要从factory方法返回promise对象。资源具有$promise
属性,这是您所需要的。所以它可能是这样的:
factmodule.factory("DashboardItemFactory", function($resource) {
var ProductItemnew = [];
ProductItemInfoResourec = $resource("http://192.168.0.194:9070/productitems/:id", {
"id": "@id",
"productid": "@productid"
}, {
update: {
method: "PUT"
}
});
return {
addProductItemnew: function(itemslist) {
var items = new ProductItemInfoResourec(itemslist);
return items.$save({ id: itemslist.productid }).$promise.then(function(respdata) {
ProductItemnew.push(respdata);
console.log("Data Saved...", respdata)
return respdata; // or return ProductItemnew;
}, function(respdata) {
console.log("Error while saving the data");
throw new Error("Error while saving the data")
});
}
}
})
只需确定您希望此承诺解决的内容:来自保存请求的原始响应或可能是ProductItemnew
数组。
答案 1 :(得分:0)
它适用于$ q
factmodule.factory("DashboardItemFactory",function($resource,$q){
var ProductItemnew=[];
ProductItemInfoResourec=$resource("http://192.168.0.194:9070/productitems/:id/:itemid",
{"id": "@id","productid":"@productid"}, {update: {method: "PUT"}});
return{
addProductItemnew:function(itemslist){
var dfr = $q.defer();
var items = new ProductItemInfoResourec(itemslist);
items.$save({"id":itemslist.productid},function(respdata){
console.log(respdata)
ProductItemnew.push(respdata);
dfr.resolve(ProductItemnew);
console.log("Data Saved...")
return dfr.promise;
},function(respdata){
console.log("Error while saving the data");
});
}
}
})