Home > Enterprise >  Angular DELETE API request doesn't clear my cart
Angular DELETE API request doesn't clear my cart

Time:01-31

In the cart component of my app I have an "Clear cart" button. I am trying to clear the cart with a API call that sends a delete request to the API.. My compiler isn't showing me any errors and the console of web browser also isn't showing any errors... but when I click the "Clear cart" button nothing happens.. the items stay in my cart...

What am I doing wrong?

here is the code:

cart.service.ts:

  clearCart() {
    return from(Preferences.get({key: 'TOKEN_KEY'})).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        return this.httpClient.delete<ShoppingCart>(`${environment.apiUrl}cart`, {headers, observe: 'response'});
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', {replaceUrl: true});
        }
        return EMPTY;
      }),
    );
  }

cart.component.ts:

  clearCart() {
    this.cartService.clearCart();
  }

And html file just in case :)

  <ion-button fill="outline" color="medium" slot="end" size="small" shape="round" (click)="clearCart()">
    Clear cart
    <ion-icon slot="end" name="trash-outline"></ion-icon>
  </ion-button>

Here is the model of cart:

export interface ShoppingCart {
  total_products: number;
  totals: number;
  notes: string;
  shipping_method: string;
  products: Product[];
}

CodePudding user response:

In order to clear the cart, you need to subscribe to the observable that is returned by the clearCart method in the CartService.

clearCart() {
  this.cartService.clearCart().subscribe(() => {
    // You can update your cart data here
  });
}

make sure to update your local cart also after the API called passed.

  • Related