我有一个 Ionic 3 应用程序,我在其中存储了 SQLite 中的对象数组。
我的 this.data 数组(在下一节中解释)如下所示:
[
{
guid: "xy",
images: [
{ guid: 0, uploaded: true },
{ guid: 1, uploaded: true }
],
},
{
guid: "xz",
images: [
{ guid: 0, uploaded: false },
{ guid: 1, uploaded: false }
],
}
]
所以一个对象又具有一个 guid 和一个对象数组。更新项目后,我想将所有项目保存到存储以及上传器类的变量中。上传器类有一个 this.data 和 this.key 属性。
这是有问题的部分的片段:
updateItem(value){
// search for the index of the item in the array
var index = this.data.findIndex((item) => {
return item.guid == value.guid;
});
if(index >= 0){
// update the item in the array with the changed one
this.data[index] = value;
// this works fine, prints with the updated item
console.log(this.data);
// it supposed to save the whole array with the changed items
return this.storage.set(this.key, this.data).then(() => {
// for debug I read the data again - same happens after app restart
this.storage.get(this.key).then((data) => {
// this logs the initial, unchanged items
console.log(data);
});
});
}
return Promise.reject(new Error('error'));
}
首先,它搜索this.data
数组中项目的索引,如果找到,则覆盖数组中的项目。然后它尝试将其保存到存储中。出于调试目的,我读取了存储和 console.log。
将“xz”对象的图像设置为 后uploaded = true
,我调用updateItem(secondItem)
.
从第一个console.log
我看到“xy”和“xy”对象的图像都上传了:true。storage.set 被调用,在 storage.get 中,初始状态发生。“xy”对象的图像已上传:true,但“xz”对象的图像为false。重新启动我的应用程序后,此状态再次加载。
如果 this.data 中只有一个对象,updateItem 可以正常工作,例如我将存储设置为上传:false,然后更改属性,调用updateItem(firstItem)
,它保存上传状态。但如果数组中有多个对象,则只保存一个。
我尝试将其保存为 JSON,并在我读回时进行解析,但结果是相同的。
我最终克隆了数组,然后保存了克隆,然后将克隆分配给了原始数组。这解决了我的问题。
updateItem(value){
// search for the index of the item in the array
var index = this.data.findIndex((item) => {
return item.guid == value.guid;
});
var newData = this.data.slice();
if(index >= 0){
// update the item in the array with the changed one
newData[index] = value;
// it supposed to save the whole array with the changed items
return this.storage.set(this.key, newData).then(() => {
this.data = newData;
// for debug I read the data again - same happens after app restart
this.storage.get(this.key).then((data) => {
// this logs the initial, unchanged items
console.log(data);
});
});
}
return Promise.reject(new Error('error'));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句