我需要在电子商务Web应用程序中使用session for add to cart选项。会话未获得更新。直到现在我已经实现了这个:
onClickCart() {
this
.cartService
.getCartDetails()
.subscribe((data) => {
localStorage.setItem('cartProducts', JSON.stringify(this.productInfoCart));
console.log("Session data: ",localStorage.getItem('cartProducts'));
});
}
可能是问题是您没有使用最新数据更新productInfoCart
this.productInfoCart = []; // initialize
onClickCart(){
this
.cartService
.getCartDetails()
.subscribe((data) => {
//this.productInfoCart = data; //add this line
// if you want to add new item to cart
this.productInfoCart.push(data);
localStorage.setItem('cartProducts', JSON.stringify(this.productInfoCart));
console.log("Session data: ",localStorage.getItem('cartProducts'));
});
}
如果我理解你的问题,那么这应该适合你https://stackblitz.com/edit/angular-srslhc?file=src%2Fapp%2Fapp.component.ts