我想这是一个简单的JavaScript问题,但仍然......我无法弄明白,我尝试了一切(我猜不是)......
我正在尝试将多个项目添加到存储在Ionic Storage中的this.cart
(如LocalStorage)。
当我向购物车添加2件商品时:
updateCart(id, qty) {
this.storage.get('cart').then((result) => {
if(result) {
this.cart = result;
}
else {
this.cart = [];
}
this.cart.push({
id: id,
qty: qty
});
});
this.storage.set('cart', this.cart);
this.storage.get('cart').then((result) => {
console.log(JSON.stringify(result));
});
}
它返回:
[{"id":"48131","qty":1}]
而不是:
[{"id":"48130","qty":1},{"id":"48131","qty":1}...]
答案 0 :(得分:0)
将其移至回调中,
this.storage.get('cart').then((result) => {
this.cart = result;
this.cart.push({
id: id,
qty: qty
});
});
答案 1 :(得分:0)
updateCart(id, qty) {
this.cart = [];
this.storage.get('cart').then((result) => {
this.cart.push(result);
});
this.cart.push({
id: id,
qty: qty
});
this.storage.set('cart', this.cart);
this.storage.get('cart').then((result) => {
console.log(JSON.stringify(result));
});
}