Ionic 3 存储装置并变得怪异

Ionic 3 storage set and get acting weird

我有一个 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 和一个对象数组。更新项目后,我想将所有项目保存到存储以及上传器 class' 变量中。上传者 class 有 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" 对象的图像都已上传:正确。 storage.set 调用,在 storage.get 内部,出现初始状态。 "xy" 对象的图片已上传:正确,但 "xz" 对象的图片为假。 在我重新启动我的应用程序后,此状态再次加载。

如果this.data中只有一个对象,updateItem可以正常工作,比如我设置storage为uploaded: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'));
}