【发布时间】:2018-05-04 12:05:38
【问题描述】:
我在 ionic2 存储中遵循以下示例:https://ionicframework.com/docs/storage/
我正在从表单页面获取对象参数,将其添加到 myBOTs 变量并保存整个对象数组,以便在页面刷新时使用它来填充列表。
我在构造函数中所做的只是调用存储来查找当前值以填充列表。
id: any;
icons: string[];
myBOTs: Array <{type: string,BOTdate: string, setReminder: boolean, icon: string}>;
constructor(public navCtrl: NavController, public navParams: NavParams, private storage: Storage) {
this.myBOTs=[];
this.storage.get('myBOTs').then((values)=>{
if(values!==null){
for(let i = 0;i < values.length;i++){
this.myBOTs.push({
type: values[i].type,
BOTdate: values[i].BOTdate,
icon: this.icons[Math.floor(Math.random() * this.icons.length)],
setReminder: values[i].setReminder
})
}
}
})
}
问题出在this.storage.set('myBOTs',this.myBOTs)下面。当我尝试 console.log(values) 在 .set 之后检索数据时,只有数组的最后一个对象被保存。
我在想离子存储可能无法在 .set 中存储对象数组?如果不是,那似乎是什么问题?
ionViewDidLoad(){
if(this.navParams.get('type')!==undefined){
let addedBOT = [];
addedBOT['type'] = this.navParams.get('type');
addedBOT['BOTdate'] = this.navParams.get('BOTdate');
addedBOT['setReminder'] = this.navParams.get('setReminder');
this.myBOTs.push({
type: addedBOT['type'],
BOTdate: addedBOT['BOTdate'],
icon: this.icons[1],
setReminder: addedBOT['setReminder']
})
this.storage.set('myBOTs',this.myBOTs);
this.storage.get('myBOTs').then((values)=>{
console.log(values);
})
}
}
【问题讨论】:
-
你在哪里初始化 this.myBOTs?这是一个空白数组吗?当你推到它时,你确定它在这个数组中有一个先前的值吗?顺便说一句,this.storage.set 是异步的,就像 get 一样。所以你不能保证 console.log(values) 在 set 方法完成后发生。
-
是的。我注意到 storage.set 是异步的。但是是的,刷新后的结果仍然只是数组的最后一个对象。
-
是这条线吗? myBOTs: Array ;
-
还有这一行?:this.myBOTs=[];
-
如果存储中有值,会在构造函数中加上.get。如果不是,它将只是一个空数组。
标签: javascript angular ionic-framework