Ionic 3存储:如何正确获取JSON对象数组?

时间:2018-04-13 16:39:29

标签: angular ionic-framework ionic3

我有以下数组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);

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

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

代码出了什么问题,以便它返回Country [5]。

2 个答案:

答案 0 :(得分:1)

请参阅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并使用原生选项。

答案 1 :(得分:-2)

我建议您使用localStorage

根据您的需求设定值:

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

获得价值:

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

希望你能提供帮助