lrefopam
lrefopam

Reputation: 531

Angular Array updates incorrectly after delete

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();
}

Upvotes: 0

Views: 54

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

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 */);

}

Upvotes: 1

Related Questions