【问题标题】:Ionic 3 Storage: How to correctly get array of JSON objects?Ionic 3 Storage:如何正确获取 JSON 对象数组?
【发布时间】:2018-09-24 02:05:21
【问题描述】:

我有以下数组 JSON 对象,并尝试使用 Ionic 存储将它们保存在本地:

Country[5]
0: {record_id: "1", local_TimeStamp: "16:00:00", country: "USA"}
1: {record_id: "2", local_TimeStamp: "17:00:00", country: "Japan"}
2: {record_id: "3", local_TimeStamp: "17:00:00", country: "Korea"}
3: {record_id: "4", local_TimeStamp: "15:00:00", country: "Thailand"}
4: {record_id: "5", local_TimeStamp: "16:00:00", country: "China"}

代码:

export class HomePage {
localarray: any = []; 

constructor(private navCtrl: NavController, private navParams: NavParams,

私有存储:存储){ }

this.storage.set('localrows', JSON.stringify(this.Country));  

// Try to get the whole array JSON object back:
let TIME_IN_MS = 2000;
let someTimeout = setTimeout( () =>
{ 
  this.storage.get('localrows').then( (data) => {
    this.localarray.push(JSON.parse(data))});
  console.dir(this.localarray);
}, TIME_IN_MS);

而不是预期的返回 Country[5]。
我从控制台日志中得到了这个结果:

Array(0)
0
:
(5) [{…}, {…}, {…}, {…}, {…}]  <= The original array JSON Objects stored here !

代码有什么问题,所以它会返回 Country[5]。

【问题讨论】:

    标签: angular ionic-framework ionic3


    【解决方案1】:

    我想建议你使用localStorage

    为您的需求设定值:

    window.localStorage.setItem('localrows',JSON.stringify(this.Country));
    

    并获得价值:

       this.localarray =JSON.parse(window.localStorage.getItem('localrows'));
    

    希望对你有所帮助

    【讨论】:

    • 感谢乌特保罗。我试过但它返回: Array(0) length : 0
    • @LHLK 打印 console.log(this.localarray);内部承诺
    • 我建议为此使用 localstorage ...。如果您使用存储,那么您需要让提供者将此数据放入您的变量中...
    • 好的。我是 Ionic 的新手,我会尝试将其放入现有的 http 提供程序中...嘿,谢谢...
    【解决方案2】:

    请参阅https://ionicframework.com/docs/storage/ 上的文档

    您必须先安装并设置它:

    ionic cordova plugin add cordova-sqlite-storage
    
    npm install --save @ionic/storage
    

    将其包含在您的 app.module.ts 导入中:

    import { IonicStorageModule } from '@ionic/storage';
    
    // Inside of your @NgModule
    imports: [
        IonicStorageModule.forRoot() // Add this
    ],
    

    然后,在您使用它的页面上,像这样引用它:

    public user: any = {};
    constructor(private storage: Storage)
    

    你可以像这样检索数组:

    storage.get('user').then((userdata) => {
        this.user = userdata;
    });
    

    如果你必须将它作为一个数组,你总是可以从 JSON JSON.parse(this.user) 解析它

    希望这将帮助其他使用 Ionic 的人避开 localStorage 并改用原生选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-23
      • 2022-01-17
      • 2018-08-25
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多