Ionic2 本机存储存储/检索阵列



我有一个Ionic应用程序,其中我存储了一个带有本机存储的数组。此数组是对象的数组

我像这样存储它:

>>>数组 1:具有至少 50 个随机元素的 CertainType[]

this.nativeStorage.setItem('array1', { property: array1 })
   .then(
      () => { console.log('array1 stored') },
      error => { console.log('array1 not Stored',error)
});

我像这样检索项目:

this.nativeStorage.getItem('array1').then(
    array1 => {  
       //On the Sucess of getting Array1 use it to create Array2
       array2 = array1.splice(0,5); //<-- MY PROBLEM IS HERE
    },
    error => {
        console.error('Error Getting Array', error);
    }
);

我一直收到错误

我认为这是因为存储和检索的过程弄乱了数组的类型等。

我试着做选角:

..array1 as CertainType[]

-- 已编辑>>我尝试了字符串和JSON解析。

this.nativeStorage.setItem('array1', { property: JSON.stringify(array1)}).then(. . . .
array2 = JSON.parse(array1);

抛出此错误:

ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

但是我在拼接((上不断收到相同的错误。

如果我不使用存储逻辑,代码运行得很好......任何线索。我错过了什么?:/

在存储在本地存储之前使用 JSON 字符串化,因为它会返回一个承诺例如,只需这样做:

​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2);

Ionic Native Storage Documentation 让我感到困惑。

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );

我坚持阅读这本书,并在我的应用程序上使用几乎相同的代码。但是那边的"财产">这个词打破了我的地板。

我上面的好贡献者坚持(感谢上帝(使用JSON.stringifyJSON.parse来保存和检索数据。

所以我做到了,但不断出现错误。 然后我意识到:当我尝试检索数据时,我的数组存储在一个对象上。还行!但是 p-r-o-p-e-r-y 属性下。

如果我确实使用 array1.property 获得了我的 array1,我会得到我想要的东西。

最后,只需稍作改动,它就会像时钟一样工作:

this.nativeStorage.setItem('array1', JSON.stringfy(array)})
      .then(. . .
this.storage.get('array').then( array1 => {
          console.log(JSON.parse(array1));

最新更新