Clearing Out a Shopping Cart in Angular

Hey there, I have a little dilemma with my shopping cart system. I can easily add and delete products using an API. However, when it comes to deleting an item from the cart, I have to do it one by one by clicking on a button for each item, which is not very efficient. I've been trying to figure out a way to empty the entire cart at once from a function, rather than having to click on each item individually, but haven't had any luck so far as the ID becomes undefined.

My main question is whether this is even possible. I've attempted to clear the array of items by setting cartItems.length = 0 or cartItems = [], but from what I understand, this only clears a copy of the array, leaving the items still present in the cart.

I'm hoping someone can provide some insight and guide me in the right direction. Your help would be greatly appreciated. I've included a snippet of HTML and the cart service code for deleting an item below.

Cart Service

 RemoveProductFromCart(id:number):Observable<void>{
     return this.http.delete<CartItem[]>(`${this.cartUrl}/${id}`)
     .pipe(catchError(_err => of (null))
      
     );
    }

CartItem.ts

 handleRemoveFromCart(){
        alert("hit remove from cart");
          
 this.cartService.RemoveProductFromCart(this.cartItem.id)
 .subscribe(() =>
        console.log("Product with Id deleted", 
      this.cartItem.id),
        (err) => console.log(err)
        );
      
       
       
      }

HTML for Cart Item

<div class="container-md" >
   <div>
    <img class="img-fluid" [src]="cartItem.imageUrl" style="padding-bottom:5px; padding-top:50px" alt="Cart">     
      <div class="text-nowrap" style="font-size:13px; width: 400px">{{cartItem.productName}}</div> 
     {{cartItem?.size}}{{Valuesize}}
   
   <div style="font-size:13px"><strong>{{ (cartItem.price) | currency}}</strong></div>
  <div class=" float-right">
   <span><i class="fa-solid fa-trash-can" style="color:#D30169; cursor: pointer;" (click)="handleRemoveFromCart();handleReload()"></i></span>
  </div>
  </div>
  </div>

Cart HTML

<div *ngIf="cartItems.length === 0"class="alert alert-info">Your Cart is Empty</div> 
    
    <div *ngIf="product">
      <div>{{product.name}}</div>
      <input type="number" [(ngModel)]="product.num" 
        min="0"/>
    </div>   
      <div  *ngFor="let item of cartItems; let i = index">
        <app-cart-item  [cartItem]="item"></app-cart-item>  
      </div>
      
      <li class="list-group-item" style="margin-top:30px">
       <strong>Total Items {{itemTotal}}</strong>
      </li> 
      <li class="list-group-item active">
        <strong>Total: {{ cartTotal | currency}}</strong>  
      </li>
      <li class="btn btn-primary" style="height: 40px; 
        width:210px; margin-top:20px; color:ffffff">
        <a class=""  routerLink="/clothing" style="color: 
         #ffffff; cursor: pointer">Continue   
         Shopping</a>&nbsp; 
     </li>
      <li class= "btn" style="height: 40px; width:210px; 
         margin-top: 20px; background-color:#D30169">
        <a class="" routerLink="/checkout" style="color: 
          #ffffff">Go To Checkout</a>&nbsp; 
      </li>
      
    </div>
    </div>
    </div

Answer №1

Explore the world of Rxjs

cart-handling.service.ts

Set up a behavior subject to manage cart items

cartItems$ = new BehaviorSubject<CartItem>([]);

For clearing all items in the cart

  clearCart() {
    this.cartItems$.next([]);
  }

For adding or removing an item

  addToCart(cartItem: CartItem) {
    this.cartItems$.next([cartItem, ...this.cartItems.getValue()]);
  }

  removeFromCart(cartItemId: string) {
    this.cartItems$.next([this.cartItems.getValue().filter((cartItem) => cartItem.id !== cartItemId)]);
  }

cartItem-model.ts

To keep track of cart items

  cartItems:CartItem[] = []

  constructor(private cartService: CartService) {
    this.cartService.cartItems$.subscribe((v) => (this.cartItems = v));
  }

Remember to always unsubscribe

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving user ID from URL in PHP

Greetings! I am currently attempting to extract the data-id from a URL and utilize this ID to insert into a database for creating a like-dislike system. data-id="1" represents the user id. The link appears as follows: <a data-fav="<?php echo $_SES ...

Steps to activate or deactivate a button in Angular 2 depending on required and non-required fields

I am looking to have the Save button activated when the Placeholder value is set to 'Optional'. If the value is set to 'Mandatory', then the Save button should be deactivated and only become active if I input a value for that field. He ...

Ways to enhance a component by incorporating default properties in React/TypeScript

I am looking to enhance a React/TS component (specifically the @mui/x-data-grid DataGrid) by populating the classes prop with my own application classes. Initially, I thought about creating a new component called CustomDataGrid like this: import React fro ...

Updating a field within an array of objects in Node.js and MongoDB: A step-by-step guide

My main objective is to change the value of the field "done" to "true" I am currently working on a project using nodejs Below is the document for reference: { "_id" : ObjectId("5a730e55114dbc2a0455c630"), "email" : "<a href="/cdn-cgi/l/email-protect ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Combining rxjs events with Nestjs Saga CQRS

I am currently utilizing cqrs with nestjs Within my setup, I have a saga that essentially consists of rxjs implementations @Saga() updateEvent = (events$: Observable<any>): Observable<ICommand> => { return events$.pipe( ofType(Upd ...

A guide to mastering Nested Table creation in Angular

I'm in the process of creating a dynamic table using an array of data let data = [{ "criterialimitId": "3", "criteriaName": "Test", "criteriaId": "1", "criteria": "Max Wager", "type": "DAILY", "oprLimit": "2.5", "status": "1", "acti ...

Issue encountered: Unable to add MongoDB object to database

Recently, I have encountered an issue with a script that looks like this: use first_db; advertisers = db.agencies.find( 'my query which returns things correctly ); close first_db; use second_db; db.advertisers.insert(advertisers); This error mess ...

What is the best way to utilize GSON for deserializing an array containing various objects

When handling JSON data, it often comes in a specific format like the example below: [ { "albums" : [ {"id":"0", "name":"name"}, {"id":"1", "name":"name"} ], "name":"name" }, { "tracks" : [ {"id":"0", "name":"name", ...

What type of JSON format is most suitable for a complex, multi-dimensional array?

Looking for advice on how to convert an excel table into a json structure. Any recommendations on the best way to do this? https://i.sstatic.net/gRshl.png ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...

When inputting data from an Angular 6 form into Mongoose, the stored date appears to be offset by

I am currently working with Angular 6 to store form data, specifically a date. The form is sending the date as (date: "2018-07-02T00:00:00.000Z") and that's what gets saved into mongoose. However, when I retrieve all events to display on the page, the ...

Grails3 and Angular profile as the default deployment configuration

What is the most effective approach to deploy the Grails3 war with an Angular profile (specifically Angular2)? My project is in Grails 3.2.9 and runs smoothly in development mode. I'm looking for a streamlined gradle build command that can create a co ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

PHP is failing to send a JSON response, but no errors are being logged in the PHP error log or displayed in the

Hey there, I'm feeling a bit frustrated and really not a fan of Javascript at all. Can someone please help me figure out why this isn't working? It's frustrating because everything seems fine when I return a simple string instead of trying t ...

The Angular Material autocomplete panel does not disappear when autocomplete is hidden within a scrollable region

https://i.sstatic.net/0eS4M.gif Having encountered a bug, I have raised an issue for it (https://github.com/angular/components/issues/20209). I am reaching out to inquire if there exists any workaround or solution known to anyone. You can observe the pro ...

Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best. I am attempting to include a js file that imports json from an html .js import menus from '../json/menus.json'; (function () { function parseMenu(ul, menu) { fo ...

Error: TypeORM entity import token is not recognized

Currently, I am facing a peculiar error while transpiling my TypeScript code to JavaScript using TypeORM. The error message that pops up is as follows: (function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, M ...

Issue: [HPM] Context not recognized. Please specify a valid context such as: "/api" or ["/api", "/ajax"]

Suddenly, I am encountering the following error in my Angular 7 project without making any changes. Strangely, it was working fine until yesterday. Error: [HPM] Invalid context. Expecting something like: "/api" or ["/api", "/ajax"] at Object.matchContext ...

The Watchdog API detects a change in the path to monitor, resulting in double triggering for a single update

import os import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import docker import json import configparser class FileChangeHandler(FileSystemEventHandler): def on_modified(self, event): if event.is ...