我正在製作一款應用程序,可以將其視爲購物車。用戶搜索產品,他們點擊產品,他們可以選擇將其添加到購物車中。 添加完項目後,它們將返回到搜索頁面。但是,如果他們返回搜索頁面並搜索某個內容,則會在某種意義上刷新頁面,因爲發出了新的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>
我改變它到這個現在我得到這個錯誤'未捕獲(承諾):TypeError:無法讀空屬性'推''TypeError:無法讀取屬性'推'nul'在這一行'products.push (data);' – ghan
您是否使用ionic2框架來創建您的應用程序,如果是這樣,請在您的.ts文件中從'@ ionic/storage'導入{Storage};'並將此存儲注入到您的'constructor() '方法 注意:不要忘記在模塊文件中導入IonicStorageModule –