How to Store Array Data Using Ionic Native Storage?

Rong Zhao picture Rong Zhao · Jun 10, 2017 · Viewed 10.1k times · Source

I'm planning to use ionic native storage to store some translation history, whenever there's a word being translated. The translation action (date, translate word) will be store in the ionic native storage, and when I open history page, a list of translation history will be shown.

Here's the most basic code I got from the ionic official website:

export class HomePage {
  DataArray: Array<string> = [];

  constructor(public navCtrl: NavController, private storage: Storage) {

  }
  // set a key/value
  setData(){
  this.storage.set('age', 'Max');
  }
  // Or to get a key/value pair
  getData(){
  this.storage.get('age').then((val) => {
    console.log('Your age is', val);
  });
}
}

Answer

abdoutelb picture abdoutelb · Jun 10, 2017

use getItem and SetItem

export class HomePage {
  DataArray: Array<string> = [];

  constructor(public navCtrl: NavController, private storage: NativeStorage) {

  }
  // set a key/value
  setData(){
  this.storage.setItem('keyOfData', JSON.stringify(DataArray));
  }
  // Or to get a key/value pair
  getData(){
  this.storage.getItem('keyOfData').then((val) => {
    console.log('Your age is', JSON.parse(val));
  });
}
}

the refrence Ionic native storage