2017-07-25 74 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