2017-07-25 71 views
0

當用戶點擊保存按鈕時,用戶將被帶回到上一頁,其中已選擇的列表項將被刪除。那功能就在那裏。我似乎無法保存該項目被刪除。我在構造函數中'.get'這個項目。完成後,我將數據設置爲父保存功能中的保存功能,該功能在用戶選擇按鈕時發生。由於如何在拼接數據時保存到本地存儲?離子2+

存儲data.ts

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { Storage } from '@ionic/storage' 

@Injectable() 
export class StorageData{ 

    constructor(public http: Http, public storage: Storage){ 

    } 

    getDataFour(){ 
     return this.storage.get('item') 
    } 

    save(data){ 
     let newData = JSON.stringify(data); 
     this.storage.set('item', newData) 
    } 

    delete(data){ 
     this.storage.remove('item'); 
    } 
} 

home.ts

export class RiderPerformPage { 

    item: any; 
    saveAttempt: boolean = false; 
    peoples: Rider[]; 

    constructor(public toastCtrl: ToastController, public navCtrl: NavController, private menu: MenuController, public navParams: NavParams, riders: Riders, public dataService: StorageData) { 
    this.rider = navParams.get('item') 
    this.peoples = navParams.get('items') 

    this.dataService.getDataFour().then((item) => { 
     if(item){ 
      this.peoples = JSON.parse(item) 
     } 
     }) 
} 
    save(action){ 
    this.action = action 
     this.presentToast() 
     this.saveAttempt = true; 
     this.peoples.splice(
     this.peoples.indexOf(this.item), 1); 
     this.navCtrl.pop(); 

     this.dataService.delete(this.peoples); 
     this.dataService.save(this.peoples); 
    } 
} 
+0

你必須請注意存儲功能是異步的。所以如果你想保存它們,你必須使用**然後**回調函數,在你調用delete之後。你可以顯示你的**刪除**和**保存**功能嗎? –

+0

使用刪除和保存功能更新了我的文章 – userlkjsflkdsvm

回答

1

你的問題是,本地存儲功能撈出是異步的。所以會發生以下情況:您刪除了該項目,但不要等到完成後才能保存數據。但是,因爲此時刪除沒有完成,所以您可以使用已刪除的項目保存數據。

我想你不必在刪除一個項目後保存數據,因爲刪除命令會從商店中刪除項目。之後爲什麼要保存?

如果您仍想救你刪除的數據請嘗試以下後:

存儲data.ts

save(data): Promise<any> { 
    let newData = JSON.stringify(data); 
    return this.storage.set('item', newData); 
} 

delete(data): Promise<any> { 
    return this.storage.remove('item'); 
} 

home.ts

save(action){ 
    this.action = action 
    this.presentToast() 
    this.saveAttempt = true; 
    this.peoples.splice(
    this.peoples.indexOf(this.item), 1); 
    this.navCtrl.pop(); 

    this.dataService.delete(this.peoples) 
     .then(() => { 
      this.dataService.save(this.peoples); 
     }); 
} 
+0

當我刷新頁面時,它不會保存到本地存儲並重置數據。 – userlkjsflkdsvm