【发布时间】:2019-05-03 16:24:59
【问题描述】:
在我的 Angular 项目中有购物车功能。我将作为数组中的对象存储在本地存储中的每个产品。
1。所以我想从 json 对象中获取每个产品的价格(productPrice),以显示购物车中的总价格。
2。另一件事是我想从本地存储中删除特定对象,按项目 ID 删除购物车项目数组。
有什么可以帮我做的吗?
Cart.component.ts
public cartItems :any;
ngOnInit() {
if(this.cartService.getFromLocalStrorage()){
this.cartItems = this.cartService.getFromLocalStrorage();
console.log(this.cartItems); //result show in below
}
}
购物车服务.service.ts
public getFromLocalStrorage() {
const cart = JSON.parse(localStorage.getItem('cartObject'));
return cart;
}
结果 - 控制台日志
(4) [{…}, {…}, {…}, {…}]
0:
productId: 2
productName: "product 2"
productPrice: 1000
productQuantity: 9
productSelectedTypeId: 1
productSelectedTypeName: "100 ml"
////---------------------------
在本地存储中
[{productId: 2, productSelectedTypeId: 1, productSelectedTypeName: "100 ml", productQuantity: 9,…},…]
0: {productId: 2, productSelectedTypeId: 1, productSelectedTypeName: "100 ml", productQuantity: 9,…}
1: {productId: 2, productSelectedTypeId: 3, productSelectedTypeName: "300 ml", productQuantity: 1,…}
2: {productId: 2, productSelectedTypeId: 2, productSelectedTypeName: "200 ml", productQuantity: 1,…}
3: {productId: 3, productSelectedTypeId: null, productSelectedTypeName: null, productQuantity: 24,…}
【问题讨论】:
-
这与角度无关,它只是 javascript 使用
map作为下面的答案建议获取价格并使用filter从数组中删除特定对象,然后更新本地存储使用过滤后的数组...顺便说一句。我不会使用 localstorage,因为由于各种浏览器中的实现不同,它可能无法按预期工作
标签: angular typescript angular7 cart shopping-cart