When I try to add a book to my cart in Angular 2, the system is mistakenly adding a duplicate copy instead of incrementing the quantity of

In my Angular 2 bookstore application, I have a method called selectedBook(b: Books) within the BookComponent.

  • As the program runs, a table displays a list of books with each book having its own "Add to cart" button.

  • When the Add to cart button is clicked, the selectedBook(b: Books) method is invoked and the selected book is passed as a parameter.

  • The method should add the book to the cartArray (which is an array of Books model) only if it's not already in the cart.
  • When adding to the cart, if a duplicate book has its quantity decremented in the table view, it should increment in the cartArray (implementation pending).

books.model :

   export interface Books {
         id: number,
         bookId: string,
         bookName: string,
         bookQuantity: number,
         bookPrice: string,
         bookAuthor: string,
         bookPublished: string
}

selectedBook(b: Books) Method Logic:

  1. The method decrements the quantity of the selected book and adds it to the cart for the first selection.
  2. For subsequent selections, the method checks if the book with the same bookId exists in the cart. If found, it sets duplicateBook flag to true; otherwise, it adds the book to the cart.
  3. Finally, the contents of the cartArray are stored in local storage.

BookComponent :

import {Component} from 'angular2/core';

import {Books} from '../models/books.model';

@Component({
    selector: 'book',
    templateUrl: `
     <table class="table table-hover">           
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Author</th>
          <th>Publisher</th>
          <th>Actions</th>
        </tr>
        <tr *ngFor="#b of books">
          <td><a>{{ b.bookId }}</a></td>
          <td>{{ b.bookName }}</td>
          <td>{{ b.bookQuantity }}</td>
          <td>{{ b.bookPrice }}</td>
          <td>{{ b.bookAuthor }}</td>
          <td>{{ b.bookPublished }}</td>
          <td>
              <button type="button" class="btn btn-primary" *ngIf="b.bookQuantity > 0" (click)="selectedBook(b)">Add to cart</button>
              <div *ngIf="b.bookQuantity < 1">Out of stock</div>
          </td>  
        </tr>
    </table>
`
})
export class BooksComponent {

    books: Books[] = [
        { id: 1, bookId: '1', bookName: 'C', bookQuantity: 7, bookPrice: '2345', bookAuthor: 'fsdf', bookPublished: 'edsdf' },
        { id: 2, bookId: '2', bookName: 'Java', bookQuantity: 52, bookPrice: '3242', bookAuthor: 'sdfs', bookPublished: 'fghzxdffv' },
        { id: 3, bookId: '3', bookName: 'SQL', bookQuantity: 7, bookPrice: '5645', bookAuthor: 'dfghrty', bookPublished: 'ghjghj' }
    ];
    cart: Books[] = [];
    duplicateBook: boolean = false;

    selectedBook(b: Books) 
    {

        b.bookQuantity = b.bookQuantity - 1;

        if (this.cart.length == 0) {
            this.cart.push(b);
        }
        else {
            for (let e of this.cart) {
                console.log(e.bookId, "==", b.bookId);
                if (e.bookId == b.bookId) {
                    console.log("Book is in cart");
                    this.duplicateBook = true;
                    break;
                }
            }

            if (!this.duplicateBook) {
                this.cart.push(b);
            }
        }
        localStorage.clear();
        localStorage.setItem('cartItems', JSON.stringify(this.cart));

        console.log("Cart contents are : ", this.cart);
    }
}

Answer №1

Examining the entire code of the component could provide valuable insights. It’s challenging to determine the issue without it, but there appears to be a potential problem with books in this particular section of the template:

<tr *ngFor="#b of books">

It seems like the reference to books might be directing to a duplicate instead of the original object from the service.

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

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

iOS updates must always keep in mind to include updating installed PWAs

For my latest project, I developed a Progressive Web App (PWA) using Angular and implemented service worker functionality. This allows the app's files to be cached for offline use, enabling users to access the PWA even without an internet connection. ...

Issue with starting Android Studio's emulator

I'm facing an issue with my emulator not launching the AVD. When I try to open the AVD, it starts the process but then nothing happens. There are no errors, and in the task manager, I can see processes like adb.exe and emulator.exe running. This probl ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Guide to navigating to a specific module within an Angular 2 application directly from the index page

As a newcomer to angular2, I recently obtained a sample login and registration code online. However, when I run the code, it displays the index page instead of the "login" module located within the app folder. Can someone please advise me on how to redire ...

Exploring Angular2: A guide to incorporating dynamic properties with conditional logic

Currently, I am diving into Angular2. In the midst of my journey, I am facing the challenge of adding a property to a <select> only if the class property type is 'withName' If this condition holds true, the outputted select should be: < ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

Troubleshooting: Issue with reloading in MERN setup on Heroku

I successfully deployed my MERN stack application on Heroku using the following code: import express from "express"; import path from "path"; const app = express(); const port = process.env.PORT || 5000; app.get("/health-check&qu ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...

Unsubscribing from an observable within a route resolve class in Angular

Within the ngOnDestroy method, I take care to unsubscribe from an observable to prevent multiple executions of the code... ngOnInit() { this.sub = this.route.params.subscribe(params => { this.projectId = +params['id']; ...

The type 'Observable' does not contain the properties found in type 'User'

I am trying to retrieve user data from Firestore, but encountering an error The type 'Observable' is missing the following properties from type 'User': email, emailVerified, uidts(2739) user.service.ts import { Injectable } from &apo ...

Search for the enumeration type of the given string does not have an assigned index signature

I am working with a string enum where each value is associated with a display name as shown below: enum MyEnum { key1 = 'one', key2 = 'two', key3 = 'three', } const myKey: MyEnum = 'two' as MyEnum; // The val ...

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

Issue accessing member value in inherited class constructor in Typescript

My situation involves a class named A, with another class named B that is inherited from it. class A { constructor(){ this.init(); } init(){} } class B extends A { private myMember = {value:1}; constructor(){ super(); ...

What causes parameters to be undefined when making a DELETE request in my Next.js application running on version 14.1.4?

I am encountering an issue with my DELETE mapping export async function DELETE({params} : {params: {id: string}}) { try { const loanToDelete = await prisma.loan.findUnique({ where: { id: parseInt(params.id) } }) if (!loanToDelete ...

Warning: Angular Compilation Issue - Deprecation Advisory

After upgrading to Angular 13, I've been encountering this deprecation warning. TypeError: message.trim is not a function at Function.Rule.FAILURE_STRING (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:30:81) at cb (/home/app/node_modules ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Searching for NavigationEnd events specifically in Angular 12?

When using Angular 11, the following code snippet functions correctly: this.r.events.pipe( filter(event => event instanceof NavigationEnd), map((event: NavigationEnd) => event.url == ROUTES.APPLICATION)) However, when migrating to Angular 12 ...

(React Native - Expo) The hook array fails to include the most recently selected object

When I attempt to add objects to a hook within a component, it seems to be functioning correctly. However, there is an issue where the last selected object is consistently missing from the updated hook array. This behavior also occurs when removing an obje ...

Steps to implement the click functionality on the alert controller and modify the language in Ionic 4

I am currently developing a multilingual Ionic 4 app and have implemented the alert controller to display language options. However, I am facing an issue on how to dynamically change the language based on user selection. Below is my app.component.ts code ...