我已将购物车中的物品存储到 localstorage 中,并且一切正常。在cart.component.ts 中,我想打印出数组中的产品。
目前,这......
cartItem:number = 0;
cartItemFunc(){
if(localStorage.getItem('localCart') !=null){
var cartZ = JSON.parse(localStorage.getItem('localCart')as string);
this.cartItem = cartZ.length;
console.log(cartZ);
}
}
...只给我保存的本地存储中有多少项目的数量..但我需要一个存储每个项目的数组,以便我可以将其添加到 html 中。一开始我有一个手动表:
//public cartItems: cartitem[] = [
// { produktid: 1 , produtName: 'Tshirt Type A',productPrice: 4, qtty: 2 },
//{ produktid: 2 , productName: 'Figurine A',productPrice: 16, qtty: 1 },
//{ produktid: 3 , productName: 'Figurine X',productPrice: 62, qtty: 3 },
//{ produktid: 4 , productName: 'Hoodie',productPrice: 30, qtty: 2 },
//{ produktid: 5 , productName: 'Tshirt Type B',productPrice: 6, qtty: 1 }
//];
这工作得很好,但显然做得不好,所以我现在必须将项目添加到购物车中。
我试过这个,但显然它不起作用:
getCart(){
if(localStorage.getItem('localCart') !=null){
for(let i = 0; i < 10; i++){
this.cartItems[i] = JSON.parse(localStorage.getItem('localCart')as string);
}
console.log(this.cartItems); //to check if there is anything in the Array
}
}
我该怎么做,我什至如何获取每个产品的数据?就像每个产品的价格一样,因为我需要一起计算......
初始声明
cartItems: cartitem[] = [
{ produktid: 1 , produtName: 'Tshirt Type A',productPrice: 4, qtty: 2 },
{ produktid: 2 , productName: 'Figurine A',productPrice: 16, qtty: 1 },
{ produktid: 3 , productName: 'Figurine X',productPrice: 62, qtty: 3 },
{ produktid: 4 , productName: 'Hoodie',productPrice: 30, qtty: 2 },
{ produktid: 5 , productName: 'Tshirt Type B',productPrice: 6, qtty: 1 }
];
cartItem:number = cartItems.lenght;
---
this.setCart(cartItems);
this.cartItems = this.getCart();
this.cartItem = this.cartItems.lenght;
---
// 将购物车序列化并存储在 localstore 中:
setCart(cartItems:cartitem[]){
const carItemsString:string = JSON.stringify(cartItems);
localStorage.setItem('localCarts', carItemsString);
}
// 从本地存储读取购物车并反序列化
getCart(): cartitem[]{
const carts: cartitem[] = [];
if(localStorage.getItem('localCarts') !=null){
const carItemsString= localStorage.getItem('localCarts');
carts = JSON.parse(carItemsString);
//this.cartItem = cartItems.length;
//console.log(cartItem);
}
return carts;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句