我正在制作一款可以被视为购物车的应用。用户搜索产品,他们点击产品,他们可以选择将产品添加到购物车。 添加项目后,它们将返回搜索页面。但是,如果他们返回搜索页面并搜索某些内容,它会在某种意义上刷新页面,因为会发出新的HTTP请求,如果他们选择了产品,请单击“添加”,只有最后一个产品可用于存储。我相信它被覆盖了。
当用户点击添加按钮saveItem()
时会调用additems.ts
来创建一个newItem对象,并调用addItem()
,假设将其推送到items[]
数组并且将它保存到存储区。
我做错了什么?
addItem.ts
items = [];
// params passed from another page
name: string = this.navParams.get('name');
desc: string = this.navParams.get('desc');
// Called once users click on Add button in addItem.html
saveItem() {
let newItem = {
name: this.name,
desc: this.desc
};
this.addItem(newItem);
}
addItem(item) {
this.items.push(item);
this.dataService.save(this.items);
// Go back to search page. When the data is reloaded
// on this page it resets all of the items in storage
this.navCtrl.pop(Search);
}
addItem.html
<button (click)="saveItem()">Add</button>
DataService.ts。
private storage: Storage;
constructor(storage: Storage) {
this.storage = storage;
}
getData() {
return this.storage.get('products');
}
save(data){
let newData = JSON.stringify(data);
this.storage.set('products', newData);
}
// viewProducts.ts(这是我要查看存储中所有当前产品的地方) 导出类ConfirmOrderPage {
public items = [];
constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public dataService: DataStorage) {
this.dataService.getData().then((products) => {
if(products){
this.items = JSON.parse(products);
console.log("confirmorder", JSON.parse(products));
}
});
}
viewProducts.html
ion-list>
<ion-item text-wrap *ngFor="let item of items">
<h2>Name: {{ item.name }}</h2>
<h3>Product Quantity: 3 </h3>
<p>{{ item.desc }}</p>
</ion-item>
</ion-list>
答案 0 :(得分:1)
this.storage.set('products', newData);
上面的代码只会为一个键保留一个值,如果要在products下添加更多项,则将newData值视为数组。在将产品添加到本地存储之前,从本地存储中检索数据并将其设置为临时阵列,并将新产品添加到该临时阵列中并将其保存在本地存储中。现在产品密钥将有一系列产品。
答案 1 :(得分:0)
,使用以下代码:
items = [];
// params passed from another page
name: string = this.navParams.get('name');
desc: string = this.navParams.get('desc');
// Called once users click on Add button in addItem.html
saveItem() {
let newItem = {
name: this.name,
desc: this.desc
};
this.dataService.save(newItem).then(()=>{
this.navCtrl.pop(Search);
});
}
并更改dataService.ts文件的save()方法,如下所示:
save(data): Promise<any>{
return this.getData().then((products: any[]) => {
products.push(data);
return this.storage.set('products', products);
});
}
答案 2 :(得分:0)
您不能在同一个键下存储多个项目。当您尝试在同一个键下存储多个项目时,最新的项目将覆盖前一个项目。
答案 3 :(得分:0)
我知道这个问题已经写了一段时间,但是我也有类似的问题。与我从mysql或sqlite所期望的不同,这些方法仅添加一条记录...但是,然后我发现了其他相当不错的东西,并且情况并非如此(根据下面链接中的代码)。 浏览器中的本地存储索引不允许您更改或创建新的索引值,而是必须使用键,然后对值进行更改。
要注意的是,该值可以包含数组值,然后可以对它们进行索引,创建,读取,更新和删除。
为便于使用,并且无需我重写任何内容,建议您看一下西蒙的答案here from the Ionic Academy。