[英]Meteor method cannot read property “quantity” undefined
运行此流星方法时,出现错误“ TypeError:无法读取未定义的属性'quantity'”。
前端通话:
Template.listingPage.events({
"submit #add-to-cart": function(e,t){
e.preventDefault();
var quantity = parseInt($("#spinner-01").val());
var listingId = t.data._id;
if(!Session.get("cartId")){
var id = Carts.insert({ line_items: []});
Session.set("cartId", id);
}
var cartId = Session.get("cartId");
Meteor.call("addToCart", (quantity, listingId, cartId), function(err, res){
if(err){
toastr.error(err.reason, "Error");
} else{
toastr.success("Added to cart", "Success");
}
});
}
});
方法(在集合文件夹中):
Meteor.methods({
addToCart: function(quantity, listingId, cartId){
var listing = Listings.findOne(listingId);
if(quantity > listing.quantity)
throw new Meteor.Error(422, 'You cannot add that many to your cart');
var lineItem = LineItems.find({ cartId: cartId, listingId: listingId });
if(lineItem){
//in cart
var cartQuantity = lineItem.quantity;
if ( (cartQuantity + quantity) > listing.quantity)
throw new Meteor.Error(422, 'You cannot add that many to your cart');
LineItems.update({ cartId: Session.get("cartId"), listingId: listingId}, { $inc: { quantity: quantity}});
toastr.success("Added to cart", "Success");
} else{
// not in cart
lineItem = {
cartId: cartId,
listingId: listingId,
quantity: quantity,
imageId: listing.imageObj._id
}
LineItems.insert(lineItem);
Carts.update(cartId, { $inc: { count: 1 }});
}
}
});
该方法的第5行导致错误,似乎列表未定义。 当我在调用该方法的路由上订阅了列表时,为什么会这样呢? 我需要使其成为仅服务器方法吗?
调用方法时
Meteor.call("addToCart", (quantity, listingId, cartId), function(err, res){
您不应在quantity, listingId, cartId
周围加上(
)
:
Meteor.call("addToCart", quantity, listingId, cartId, function(err, res){
当您编写f(a, (b, c, d), e)
, (b, c, d)
实际上是逗号运算符 ,它计算其所有操作数,然后返回最后一个。 因此,这与f(a, d, e)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.