【发布时间】:2019-06-22 22:09:51
【问题描述】:
我正在制作一个可以被视为购物车的应用。用户搜索产品,点击产品,然后可以选择将其添加到购物车中。 添加项目后,它们将返回到搜索页面。但是,如果他们返回搜索页面并搜索某些内容,它会在某种意义上刷新页面,因为发出了新的 HTTP 请求,并且如果他们选择了一个产品,单击添加,则只有最后一个产品在存储中可用。我相信它正在被覆盖。
当用户点击添加按钮时,additems.ts 中会调用 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>
数据服务.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>
【问题讨论】: