I have two components. 1) product component that adds products to a cart. 2) A cart component that can view and remove the products that were added. My problem is that the cart component doesn't really remove the products. When I click remove, it hides the product from the view but if I navigate back to the product page and return the to cart page then I can see the product that was hidden.
Here is my code
Service
private eventSource = new ReplaySubject();
public event$ = this.eventSource.asObservable();
getAllProducts() {
return this.http.get<IProductsAvailable[]>("https://fakestoreapi.com/products")
}
public setEvent(value) {
this.eventSource.next(value);
}
Product component
ngOnInit(): void {
this.loading = true;
this.productsService.getAllProducts().subscribe({
next: (res) => {
this.loading = false;
this.productsAvailable = res;
this.dataSource.data = res;
},
error: (error) => {
this.loading = false;
alert(error);
}
})
}
addToCart(product): void {
this.productsService.setEvent(product);
}
goToCart(): void {
this.router.navigate(['cart']);
}
Cart component
cartProducts: Array<any> = [];
ngOnInit(): void {
this.productsService.event$.subscribe(product => {
this.cartProducts.push(product);
this.sum();
});
}
deleteProduct(id) {
let index = this.cartProducts.findIndex(item => item.id === id);
this.cartProducts.splice(index, 1);
this.sum();
}
Stackblitz example
CodePudding user response:
In product service, i updated replaysubject to behaviorsubject.
private eventSource = new BehaviorSubject([]);
Then in productslist component i added following variable
public products;
and in ngOnInit i initialized it with same behavior subject value
this.productsService.event$.subscribe((res) => (this.products = res));
and modified addToCart method to following
addToCart(product): void {
this.products.push(product);
this.productsService.setEvent(this.products);
}
In cart.component modified ngOnInit like following :-
ngOnInit(): void {
this.productsService.event$.subscribe((products) => {
this.cartProducts = products;
this.sum();
});
}
and changed deleteProduct method to following :-
deleteProduct(id) {
let index = this.cartProducts.findIndex((item) => item.id === id);
this.cartProducts.splice(index, 1);
this.productsService.setEvent(this.cartProducts);
this.sum();
}
Stackblitz url :- https://stackblitz.com/edit/angular-ivy-gnye61?file=src/app/cart/cart.component.ts