【发布时间】:2019-07-16 17:41:45
【问题描述】:
我有一个按钮 addToCart,它的值存储在 Localstorage 中。 如果满足某个条件,我想更新本地存储的所有传入值。
这里是函数
addToCart(itemValue) {
console.log("cart value--", itemValue);
// this.cartProduct = this.getCartProduct(itemValue.productAlias);
let count = 0;
var countValue: any;
let shipPrice = 4.75;
let result: any = [];
// console.log("cart data", this.getCartProduct(itemValue.productAlias));
var item = {
userId: this.userId,
productid: itemValue.productId,
seller: itemValue.seller,
price: itemValue.price,
sellerId: itemValue.sellerId,
productAlias: itemValue.productAlias,
productImage: itemValue.productImage,
productName: itemValue.proName,
shippingPrice: shipPrice
};
if (count > 0) {
console.log("if condition", count);
shipPrice = 1.50;
}
// console.log("cart value--", item);
if (localStorage.getItem('cart') == null) {
this.cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(this.cart));
// console.log(localStorage.getItem('cart'));
} else {
let cart: any = JSON.parse(localStorage.getItem('cart'));
let index: number = -1;
// let item = JSON.parse(cart);
console.log("item************" + cart);
for (var i = 0; i < cart.length; i++) {
let item = JSON.parse(cart[i]);
console.log("local storage value", item);
if (item.productid == itemValue.productId && item.seller == itemValue.seller) {
index = i;
break;
}
if (item.sellerId == itemValue.sellerId) {
count++;
console.log("count-----" + count);
let item = JSON.parse(cart[i]);
item.shippingPrice = 1.50;
cart[i] = JSON.stringify(item);
localStorage.setItem("cart", JSON.stringify(cart));
}
}
if (index == -1) {
// count=0;
cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(cart));
}
}
// let cartValue: any = JSON.parse(localStorage.getItem('cart'));
// console.log("cart value********", cartValue);
this.helperSvc.notifySuccess('Product Added to Cart');
this.router.navigate([`/in/product/${this.pTitle}`]);
}
我希望如果sellerId 相同,运费的值为1.50;如果任何条目具有相同的卖家 ID,运费将为 1.50, 并且对于 localstorage 中的每个条目,都必须检查条件。
这是本地存储车
{"userId":"8","productid":"1","seller":"user","price":"100","sellerId":"2","productAlias":"pure-mens-plain-shirt","productImage":"uploads/1562685351.jpg","productName":"Pure Mens Plain Shirt","shippingPrice":4.75},{"userId":"8","productid":"2","seller":"user","price":"50","sellerId":"2","productAlias":"mens-cotton-shirt","productImage":"uploads/1562685440.jpg","productName":"Mens Cotton Shirt","shippingPrice":4.75}
我希望本地存储中的任何条目都在那里,sellerid 相同,相同sellerid 的运费应更新为 1.50。
【问题讨论】:
-
恕我直言。我想说这段代码看起来毫无意义。请清楚您的要求并发布清晰简洁且有意义的代码示例。
-
现在检查我已经更新了问题
标签: javascript angular6 local-storage