2017-06-06 67 views
1

我正在製作一款應用程序,可以將其視爲購物車。用戶搜索產品,他們點擊產品,他們可以選擇將其添加到購物車中。 添加完項目後,它們將返回到搜索頁面。但是,如果他們返回搜索頁面並搜索某個內容,則會在某種意義上刷新頁面,因爲發出了新的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
this.storage.set('products', newData); 

上面的代碼將只保留一個鍵的一個值,如果你想添加更多的項目下產品密鑰將數據值視爲數組。在將產品添加到本地存儲之前,從本地存儲中檢索數據並將其設置爲臨時陣列,並將該新產品添加到該臨時陣列中,並將其保存在本地存儲中。現在產品密鑰將會有一系列產品。

在你的.ts文件
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); 
    }); 
} 
+0

我改變它到這個現在我得到這個錯誤'未捕獲(承諾):TypeError:無法讀空屬性'推''TypeError:無法讀取屬性'推'nul'在這一行'products.push (data);' – ghan

+0

您是否使用ionic2框架來創建您的應用程序,如果是這樣,請在您的.ts文件中從'@ ionic/storage'導入{Storage};'並將此存儲注入到您的'constructor() '方法 注意:不要忘記在模塊文件中導入IonicStorageModule –

0

不能存儲在多個項目同樣的鑰匙。當您嘗試將多個項目存儲在同一個鍵下時,最新的項目將覆蓋前一個項目。

相關問題