我在Angular 8项目中工作,当前的任务是在进入购物篮和支付之前将预订的数据存储到本地存储中,我有眼镜、餐厅和giftCardstypes对象。我将对象存储在localStorage中
[{,…}, {id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan",…},…]
0: {,…}
placesListContent: [{tr_id: "692741", tr_sp_id: "12535", tr_entite: "AG", tr_cat_ordre: "1", tr_cat: "Tarifs :",…}]
0: {tr_id: "692741", tr_sp_id: "12535", tr_entite: "AG", tr_cat_ordre: "1", tr_cat: "Tarifs :",…}
qte: 1
restaurant: null
spectacle: {sp_id: "12535", sp_date: "1563371131", sp_th_id: "1493", sp_cat_id: "3", sp_prod_id: "0",…}
1: {id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan",…}
amount: 60
banner: ""
designation: "spectacle + restaurant"
format: "bb"
gift: []
icon: "/uploads/fe633f32ab883aae44f154f3fead6982.png"
id: 9
qte: 4
type: "Soirée Bon plan"
2: {id: 11, designation: "spectacle + restaurant", gift: [], type: "Soirée Chic",…}
amount: 100
banner: ""
designation: "spectacle + restaurant"
format: "vv"
gift: []
icon: "/uploads/f63473b5694a420ca32fa87f415879a0.png"
id: 11
qte: 2
type: "Soirée Chic"
3: {id: 12, designation: "spectacle + restaurant", gift: [], type: "Soirée VIP",…}
这是giftcardTypes的用户界面: https://i.stack.imgur.com/yaFVd.png
addGiftToCard(type) {
type = type.type
let cardParse = JSON.parse(localStorage.getItem('cart')) || []
let index = _.findIndex(cardParse, item => item.type && item.id == type.id)
if (index == -1) {
type.qte = 1
cardParse.push(type)
} else {
cardParse[index].qte += 1
}
localStorage.setItem('cart', JSON.stringify(cardParse))
}
谁能帮帮我!
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在Angular 8项目中,您希望实现将预订数据存储到本地存储(localStorage)并在进入购物篮和支付之前能够管理这些数据。根据您的描述,您已经成功地将一些对象存入了localStorage,并且现在想要添加一个方法addGiftToCard
来处理giftcardTypes的添加逻辑。
首先,确保你已经在项目中安装并导入了lodash库,因为您使用了_.findIndex
方法。如果尚未安装,可以通过运行npm install lodash
来安装,并在需要使用的组件中导入它:
import * as _ from 'lodash';
接下来,让我们完善您的addGiftToCard
方法。这个方法应该查找是否已存在相同类型的项在cart中,如果存在则增加其数量,否则将其添加到cart数组中。修改后的代码如下:
addGiftToCard(type) {
// 获取当前cart内容或初始化为空数组
let cardParse = JSON.parse(localStorage.getItem('cart')) || [];
// 查找类型相同的项的索引
let index = _.findIndex(cardParse, item => item.type === type.type);
// 如果找到了匹配的项,则增加其数量
if (index !== -1) {
cardParse[index].qte += 1; // 或者根据需求调整增量
} else {
// 否则,创建一个新的对象并添加到cart中
let newItem = {
id: type.id,
designation: type.designation,
gift: type.gift.slice(), // 复制gift数组以避免引用问题
type: type.type,
qte: 1, // 初始化数量为1
amount: type.amount, // 假设amount是你要存储的属性
banner: type.banner,
format: type.format,
icon: type.icon
};
cardParse.push(newItem);
}
// 将更新后的cart内容存回localStorage
localStorage.setItem('cart', JSON.stringify(cardParse));
}
这段代码首先尝试从localStorage获取购物车数据,然后根据传入的type去查找是否有相同类型的项目。如果找到,则增加该项目的数量;如果没有找到,则创建一个新的对象并将其添加到购物车数组中。最后,更新后的购物车数组会被转换成JSON字符串并重新保存到localStorage里。
请根据实际情况调整上述代码中的属性名称,以确保它们与您实际的数据结构相匹配。