当用户单击保存按钮时,用户将返回到上一页,他们选择的列表项将被删除。该功能就在那里。不过,我似乎无法保存要删除的该项目。我在构造函数中".get"项目。完成此操作后,我将数据设置为用户选择按钮时发生的父保存函数中的保存函数。谢谢
storage-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');
}
}
首页
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);
}
}
您的问题是本机存储函数删除和设置是异步的。因此,会发生以下情况:您删除了该项目,但不要等到它完成并同时保存数据。但是,由于此时删除尚未完成,因此您将保存包含已删除项目的数据。
我认为您不必在删除项目后保存数据,因为删除命令会从存储中删除该项目。为什么在那之后你想保存?
如果在删除数据后仍要保存,请尝试以下操作:
storage-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');
}
首页
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);
});
}