0

I have created a shopping cart and all http operations are working. However, I have the problem that when I delete something from the shopping cart, the displayed data is only updated after a refresh of the page or when deleting another item.

shopping-cart.service.ts

public getCart(): Observable<CartRequest> {
  return this.http.get<CartRequest>(environment.apiUrl + Api.v1.cart.cart);
}

deleteFromCart(cartListItem: CartListItem) {
  this.http.delete(url + '/' + cartListItem.cartItemId)
    .subscribe(data => {
      console.log('Deleted item ', cartListItem.cartItemId);
    }, error => {
      console.log(error);
    });
}

cart-list.component.ts

public generateCart() {
  // refresh the cart if fulled
  if (this.cartItems.length > 0) {
    this.cartItems = [];
    console.log(this.cartItems);
  }

  this.shoppingCartService.getCart().subscribe((data: CartRequest) => {
    for (const a of data.cartItems) {
      const cartListItem: CartListItem = {
        cartItemId: a.cartItemId,
        image: '..',
        name: '..',
        itemNumber: '123 456 789',
        orderNumber: '265 715 365',
        quantity: a.quantity,
        units: ['Stk', 'Kg', 'mm'],
        total: '150,00'
      };
      this.cartItems.push(cartListItem);
    }
    console.log(this.cartItems);
  });
}

cart-list-item.component.ts

deleteFromCart() {
  this.shoppingCartService.deleteFromCart(this.cartItem);
  // refresh the cart
  this.cartList.generateCart();
}

1 Answer 1

1

You know API Services are async. But you try to refresh your cart directly after you started the call. Please refresh within the callback.

deleteFromCart(cartListItem: CartListItem) {
    this.http.delete(environment.apiUrl + Api.v1.cart.cart + '/' + 
     cartListItem.cartItemId).subscribe(data => {
      // REFRESH HERE
    }, error => { console.log(error); });

Alternatively you can delete your item optimistically in your frontend. But in this case you need to modify the data holder directly (slice)

deleteFromCart() {
 this.shoppingCartService.deleteFromCart(this.cartItem);

// optimistic deletion
this.cartItems.slice(/* respective arguments */);

}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah that's why! Thank you. I updated my delete Method to return an Observable and subscribed to it in the item component and it's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.