What is the best way to modify an object's property before including it in a new array?

Within my Angular App, there exists a list of objects that can be added to the cart. When an item is added to the cart, I save the cart in local storage. However, a problem arises when the item is added from the product detail page where the item image is large, leading to a localstorage error due to memory constraints.

To address this issue, I plan to set the item's image to null when it is added from the item detail page. Then, when the user navigates to the cart, I will call an API to retrieve images for all products without the image.

The challenge lies in the addToCart function within my cart service:

  addToCart(product: Plu, big_image?: boolean): any{
    if (big_image) {
      product.img = null;
    }
    this.carrello.plu.push({ ...product});
    this.cartTotal();
  }

As the product: Plu is a reference, setting the image to null also affects the actual Plu in the detail item page. Therefore, the best solution would involve setting the Plu image to null before adding it to this.carrello.plu.

One potential solution could be:

  addToCart(product: Plu, big_image?: boolean): any{
    const clone = Object.assign({}, product);
    if (big_image) {
      clone.img = null;
    }
    this.carrello.plu.push({ ...clone });
    this.cartTotal();
  }

I am considering if this is the optimal solution...

Answer №1

Here is a suggested approach:

addToBasket(item: Product, largeImage?: boolean): any{
  this.shoppingCart.items.push({ ...item, image: largeImage ? null : item.image});
  this.calculateTotal();
}

Quick tip: It's recommended not to utilize null in Angular and Typescript; instead, opt for undefined

Answer №2

To achieve this functionality, a simple method can be implemented as follows:

addToCart(product: Item, showBigImage?: boolean): any{
    const copy = { 
       ...product, 
       img: showBigImage ? null : product.img
    };

    this.shoppingCart.items.push(copy);
    this.calculateTotal();
}

The spread operator in JavaScript functions similarly to Object.assign.

For more information, visit:

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

How can a modal be opened in Angular 6 using only Bootstrap, without the use of Material?

In my left bar component, there is a button to open a modal. How can I make sure that the modal is opened when the button is clicked, but not within the component itself? ...

Guide on accessing model or view variables in Angular 4 to enable bidirectional data binding

I need to retrieve the value of a textarea in the component class by triggering a button click function. HTML <div class="container"> <div class="row"> <div class="col-lg-4 col-sm-12"> <textarea class="form-control" p ...

Troubleshooting issues encountered while sending HttpClient Get Requests from Angular Front-End to Node.js Back-End

I am encountering an issue where I keep getting the error message "Cannot GET /" on my local host URL when attempting to send a HttpClient get request from my Angular front-end to my Node.js back-end endpoint. Despite the fact that my back-end endpoint suc ...

Failed to retrieve information from the Service for the component

My goal is to retrieve data from a service and display it in a component. Below is the code for my service: Service.ts export class PrjService { tDate: Observable<filModel[]>; prjData:Observable<filModel[]>; entityUrl; constructor(){ this ...

The type 'elementfinder' cannot be assigned to a parameter of type 'boolean'

Currently, I am working on a function that checks if a checkbox is selected. If it's not checked, then the function should click on it. However, I encountered an error message stating "argument of type 'elementfinder' is not assignable to pa ...

display a list of items in the dashboard using Angular 2 md-sidenav when clicked

I've successfully implemented a sidebar navigation menu in Angular 2, resembling the image shown in the link below: https://i.sstatic.net/KFvJQ.jpg UPDATE: However, I'm facing an issue where clicking on a category link within the sidebar doesn ...

Unable to retrieve HTTP call response during debugging, although it is visible in the browser

When I send an HTTP request to create a record, I am able to see the added record id in the Network section of browsers like Chrome and Firefox. However, when I try to debug the code and retrieve the same id value, I encounter difficulties. I have tried us ...

ES6: Leveraging the power of await in conjunction with callbacks

Check out this TypeScript wrapper for vue-router: abstract class RoutingHelper { // ... public static redirectToNamedRoute(targetRouteName: AnyValueOf<typeof NamedRoutes>): Promise<void> { return new Promise<void>((resolve: () ...

The list of countries does not appear in the NgxIntlTelInput plugin for Angular

I am encountering an issue with the Country list not showing in my form while using NgxIntlTelInput Angular plugin to input a telephone number along with the country code. Here is the relevant code snippet: <form #f="ngForm" [formGroup]=" ...

Integrating React frontend with Node JS backend on Kubernetes platform

Seeking guidance on the best approach for making API requests from a React Frontend Application to a Node JS backend application in a Kubernetes environment. Both are hosted within the same container, following this dockerfile structure: COPY frontend/pack ...

Encountering an issue while trying to npm install, can someone offer some assistance?

npm code E404 npm 404 Error - GET https://registry.npmjs.org/tsnode - Resource not discovered ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

The functionality of the Request interface appears to be malfunctioning

Hey there, I'm currently working on building an API using Express and TypeScript. My goal is to extend the Request object to include a user property. I've done some research on Google and found several posts on StackOverflow that explain how to d ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

Leveraging Inversify for implementing a Multiinject functionality for a class with both constant and injected parameters

In my Typescript code, I have an insuranceController class that takes a multi inject parameter: @injectable() export class InsuranceController implements IInsuranceController { private policies: IInsurancePolicy[]; constructor(@multiInject("IInsu ...

Tips for eliminating unicode characters from Graphql error messages

In my resolver, I have implemented a try and catch block where the catch section is as follows: catch (err: any) { LOG.error("Failed to get location with ID: " + args.id); LOG.error(err); throw new Error(err); ...

Transferring data between components in Ionic 2: Service to Page

My service code includes two functions - one for creating a native storage with IP and port, and the other for retrieving values from the native storage. DatabaseService export class DatabaseService { ... public ip: string; public port: string; . ...

An iron-dropdown made of polymer featuring a trigger button made of paper-icon-button

I am facing an issue on my Angular site where I have integrated Polymer. I am trying to add a notifications section to the header, but I am struggling to make the button functional. How can I bind the click event of the button to trigger the dropdown? Thi ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...