angular - 在将对象属性添加到新数组之前如何更改对象属性?
问题描述
在我的 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();
}
但我会知道这是否是最好的解决方案......
解决方案
你可以简单地做这样的事情:
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
推荐阅读
- typescript - Typescript 的 VS 代码 - 将目标设置为 es6 会创建显示 es6 警告/问题的 js 文件
- c# - 拉入提交后如何防止使用的 dll 引用从项目中删除?
- python - 使用 scikit-learns SimpleImputer 时输入错误
- javascript - 学生注册挂钩后如何在wordpress中的“添加新用户”表单上注册家长
- c# - 当另一个选项卡禁用时,如何使用 XAML 触发器更改 TabControl 索引?
- python-3.x - 无法使用美汤从网页中提取 div 标签?
- javascript - 测试 Redux 连接的 Typescript 文件
- c# - 在 Collections 和 Regex.Match 方法之间传递数据
- android - ViewPager 有两个包含一组卡片的片段
- c# - 方法应该等到另一个方法启动的另一个方法完成