【问题标题】:Ionic2 Native Storage storing/retrieving ArraysIonic2 Native Storage 存储/检索数组
【发布时间】:2018-01-20 03:43:51
【问题描述】:

我有一个 Ionic 应用程序,我在其中存储了一个带有 Native-Storage 的 Array。 这个Array是一个对象数组。

我是这样存储的:

>>> array1:CertainType[] 至少有 50 个混洗元素

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>)

但我在 splice() 上不断收到同样的错误。

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

【问题讨论】:

    标签: ionic-framework ionic2


    【解决方案1】:

    在存储到 localStorage 之前使用 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);
    

    【讨论】:

    • 我知道 :D Bu 数组有超过 5 个。顺便说一下,元素都被打乱了。我需要获取并删除前 5 个元素。我只是展示了简化的代码。这里还有其他逻辑在起作用 :D 有什么猜测吗?
    • 我不断收到错误,这次是 JSON.Parse。错误错误:未捕获(承诺中):SyntaxError:位置 1 处 JSON 中的意外标记 o SyntaxError:JSON.parse 中位置 1 处 JSON 中的意外标记 o()我将使用我的代码编辑问题使用。
    • 你的回答是对的。 Ionic 文档关于他们使用的示例是错误的。我用我面临的问题来回答我自己的问题。谢谢哥们!! :D
    【解决方案2】:

    Ionic Native Storage 文档让我很困惑。

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

    我坚持书本并在我的应用程序上使用几乎相同的代码。但是那边的“财产”这个词让我崩溃了。

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

    所以我做到了,但一直出错。然后我意识到:当我试图检索数据时,我的数组存储在一个对象上。好的!但是 UNDER 一个 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2016-08-23
      • 2019-04-25
      • 2018-02-22
      • 2017-11-12
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多