首页 > 解决方案 > 在将对象属性添加到新数组之前如何更改对象属性?

问题描述

在我的 Angular 应用程序中,我有一个可以添加到购物车的对象列表,当将商品添加到购物车时,我将购物车保存在本地存储中,问题是如果该商品是从产品详细信息中添加的(其中项目图像是大图像)很快我将收到本地存储错误,这将表明它的内存已结束。

所以我会这样管理它,当从项目详细信息中添加项目时,我会将其图像设置为 null,然后当用户更改其到购物车的路径时,我会调用 API 来获取所有没有图像的产品的图像.

问题是我在购物车服务中将商品添加到购物车的功能如下所示:

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

但是作为产品:Plu 是一个参考,详细项目页面中实际 Plu 的图像也将设置为 null。

那么在将 Plu 图像添加到之前将其设置为 null 的最佳解决方案是this.carrello.plu什么?

我在想这样的事情:

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

但我会知道这是否是最好的解决方案......

标签: angulartypescript

解决方案


你可以简单地做这样的事情:

addToCart(product: Plu, big_image?: boolean): any{
    const clone = { 
       ...product, 
       img: big_image ? null : product.img
    };

    this.carrello.plu.push(clone);
    this.cartTotal();
}

扩展运算符的工作方式类似于 Object.assign

参考:https ://basarat.gitbook.io/typescript/future-javascript/spread-operator


推荐阅读