我能够在本机存储中将一个数组保存在一个页面中并将其放入另一个页面中。
将数据保存在一个页面中的功能(不离开此页面,我可以推送新元素并正确存储):
saveWordStorage (OrWord,TrWord){
this.originalWordDataArray.push(OrWord);
this.translatedWordDataArray.push(TrWord);
this.natStorage.setItem("originalWord",JSON.stringify(this.originalWordDataArray))
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
this.natStorage.setItem("translatedWord",JSON.stringify(this.translatedWordDataArray))
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
}
在其他页面中获取数据的功能:
getData(){
this.natStorage.getItem('originalWord').then((val) => {
this.originalWordDataArray = JSON.parse(val);
this.natStorage.getItem('translatedWord').then((val) => {
this.translatedWordDataArray = JSON.parse(val);
this.joinArray(this.originalWordDataArray,this.translatedWordDataArray);
});
});
}
问题是我想在导航到其他页面后在同一个键中添加更多元素。我的意思是,保存页面中的一些元素" A",然后通过其他页面导航并返回页面" A"并保存更多元素。它只存储最后一页中添加的元素" A"。
我尝试先从存储中获取数组,推送新元素并重新设置但没有成功(基本上,加入以前的功能):
getData(OrWord,TrWord){
this.natStorage.getItem('originalWord').then((val) => {
this.originalWordDataArray = JSON.parse(val);
this.originalWordDataArray.push(OrWord);
this.natStorage.getItem('translatedWord').then((val) => {
this.translatedWordDataArray = JSON.parse(val);
this.translatedWordDataArray.push(TrWord);
this.natStorage.setItem("originalWord",JSON.stringify(this.originalWordDataArray))
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
this.natStorage.setItem("translatedWord",JSON.stringify(this.translatedWordDataArray))
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
});
});
}
我正在使用import { NativeStorage } from '@ionic-native/native-storage';