I have a dilemma, I’m able to delete item from database collection carts, I figured out the reason I have to reload the cart to get update on cart, this is because item is being removed from database but not from the array. I tried a number of ways to delete from array but its not working for me. I tried using splice as well as indexOf. Can someone please point me in the right direction I would greatly appreciate it. I have included a snippet of necessary code.
CartItemComponent:
cartitems$: Cartitems[] = []
cartItems: CartItem [] = []
handleRemoveFromCart(){
alert("hit remove from cartitem");
/* this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe(() =>
console.log("Product with Id deleted", this.cartItem._id
//this.cartitems$ = this.cartitems$.splice(this.cartItem._id) does not work
);*/ //didn't work
this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe((index =>{
console.log("Product with Id deleted", this.cartItem._id),
this.result = this.cartitems$.findIndex(p => p._id === this.cartItem._id);
if(this.result > -1){
this.cartitems$.splice(this.result, 1);
alert("Remove from array")
}
}
}
cartService:
RemoveProductFromCart(_id:string){
alert("show deleted item" + _id);
return this.http.delete<Cartitems[]>(this.rootUrl + '/getProducts/removecartitems/' + _id);
/* This goes back to calling function so I can try to delete from collection*/
}
2
Answers
Using
tap
from RxJS andfilter
instead ofsplice
filter
creates a new array without the specified carItemId while thetap
operator allows you to perform a "side effect", in this case, deleting the item. Also,RemoveProductFromCart
returnsvoid
, since there’s no need to return a new array after adelete
request.RxJS – tap
The naming convention you are using for your
cartitems
seems wrong, you usually use$
when the type is anObservable
, if that’s a typo from your end and it is indeed an observable, then you have to update thecartItems
by sending a new updated array like so:component.ts
component.html
In the first approach, it subscribes manually to the http response from the server and in it, you
next
it with the updated cart items.The second one, you don’t
subscribe
, instead youpipe
it and return a finalObservable
holding the updated cart items.Additionally, you should also handle the possible scenario of an error with
catchError
, but I didn’t implemented since I am not sure if you are already doing that in your project.As a side note, I am not sure why you have 2
cartItems
declared in your component, both seems to be of the same type, the only differences are the names, one doesn’t have$
the other one does it which is very confusing.