I'm facing a peculiar issue with my code. I have component A and service B. I send an object from component A to service B, where it gets pushed into an array. Changes made to the data in the array are reflected back in the A component.
Here's the setup: In component A, I have an array called
returnedArray: ProductModel[] = [];
which contains some initial data.
In the template, I use ngFor
to iterate over this array: *ngFor="let products of returnedArray; let i = index">
There's a button in the template that triggers a method:
<button class="btn btn-primary btn-block"
(click)="addToShoppingList(products)">
add
<span class="op-icon op-shopping-cart"></span>
</button>
Here's the method code:
addToShoppingList(product: ProductModel) {
this.shop.setProductCart(product);
this.messageService.add('Product added to cart!!!');
}
The setProductCart
method resides in the ShopCartService
:
setProductCart(product: ProductModel) {
for (let i = 0; i < this.productCart.length; i++) {
if (this.productCart[i].product_name == product.product_name) {
this.productCart[i].numberOfProduct++;
}
}
this.productCart.push(product);
}
Here's my productCart array:
private productCart: ProductModel[] = []
The issue arises when I execute
this.productCart[i].numberOfProduct++;
, causing changes to be reflected in the A component as well.