[英]ionic2 Storing Array of Objects in Storage
我在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);
})
}
}
我已經解決了
問題在於構造函數和ionViewDidLoad都在頁面加載時被異步調用。 這導致從表單頁面進行的數據推送首先添加到this.myBOT中,然后才從構造函數列表中的存儲中獲取並加載結果。
所以這是我的解決方案。 我要做的是在將表單數據添加到列表之前,將代碼添加到函數中,並向列表生成函數添加回調。
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=[];
let e = this;
this.generate_list(function(){
e.add_item();
})
}
列表生成功能,用於設置存儲中的先前列表項。
generate_list(callback){
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
})
}
}
callback();
})
}
然后從navParams的數據中添加新項目
add_item(){
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);
console.log('storage added');
}
}
完美解決。 可能會幫助某人,因為這是一種很常見的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.