Ionic 3 хранилище и получай странные - PullRequest
0 голосов
/ 16 ноября 2018

У меня есть приложение 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, если он найден, а затем переопределяет элемент в массиве. Затем он пытается сохранить его в хранилище. В целях отладки я прочитал файл storage и console.log.

После того, как я установил изображения объекта "xz" на uploaded = true, я вызываю updateItem(secondItem).

С первого console.log я вижу, что все изображения объектов "xy" и "xy" загружены: true. Вызывается storage.set, а внутри storage.get возникает начальное состояние. Загружены изображения объекта "xy": true, но объекты "xz" - false. После перезапуска приложения это состояние загружается снова.

Если в this.data есть только один объект, updateItem работает нормально, например, я устанавливаю хранилище с помощью uploaded: false, затем меняю атрибуты и вызываю updateItem(firstItem), это сохраняет загруженное состояние. Но если в массиве более одного объекта, он сохраняет только один.

Я попытался сохранить его как JSON и выполнить синтаксический анализ при чтении обратно, но результаты остались прежними.

1 Ответ

0 голосов
/ 31 декабря 2018

Я закончил клонированием массива, затем сохранил клон и затем назначил клон исходному массиву. Это решило мою проблему.

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'));
}
...