Angular单列表项跨服务及组件转移至购物车问题求助
Hey there! I see the issue right away—you're currently passing the entire list of games to your cart service every time you click "Add To Cart", instead of just the specific game you clicked on. Let's fix this step by step:
1. Pass the clicked game item in your template
First, update the button in buyGame.html to pass the current buying item to the click handler (I also cleaned up a small syntax issue with the semicolon in your class attribute):
<button class="btn btn-danger pull-left" (click)="onAddToCart(buying)">Add To Cart</button>
2. Update the component's click handler
In buyGame.component.ts, modify the onAddToCart method to accept a single gameBuy item instead of the whole array, then pass that item to your service:
onAddToCart(selectedGame: gameBuy){ this.service.addItemToCart(selectedGame); }
3. Adjust the gameService to handle single items
Right now your addItemToCart method expects an array, so let's update it to accept a single item. Since your cart service's addItem method uses the spread operator (...cart), we can wrap the single item in an array to match its expected input:
addItemToCart(game: gameBuy){ this.cartSer.addItem([game]); // Wrap single item in array to match cartService's input }
Optional: Make cartService support single items directly (cleaner approach)
For better flexibility, you can update your cartService to handle both single items and arrays. This way you don't have to wrap items in arrays every time:
addItem(item: gameBuy | gameBuy[]){ if(Array.isArray(item)){ this.cart.push(...item); } else { this.cart.push(item); } this.cartChanged.emit(this.cart.slice()); }
With this change, your gameService's addItemToCart can just pass the single item directly:
addItemToCart(game: gameBuy){ this.cartSer.addItem(game); }
4. Ensure your cart component updates in real-time
I noticed your CartComponent only fetches the cart items once on ngOnInit. To make sure the cart updates automatically when you add an item, subscribe to the cartChanged emitter in cartService:
ngOnInit() { this.cart = this.service.getCartItem(); // Subscribe to changes to refresh the cart display this.service.cartChanged.subscribe(updatedCart => { this.cart = updatedCart; }); }
That's it! Now when you click "Add To Cart" on any game, only that specific item will be added to your cart, and your cart component will update immediately to reflect the change.
内容的提问来源于stack exchange,提问作者Rohit B

