Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Store Array Data Using Ionic Native Storage?

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);
  });
}
}
like image 891
Rong Zhao Avatar asked Jun 10 '17 12:06

Rong Zhao


People also ask

How do you use native storage in ionic?

Using Storage in Ionic App To store the data on local storage or to access Native Storage methods, you have to import the NativeStorage module from the '@ionic-native/native-storage/ngx' package; likewise, add the NativeStorage package into the constructor() method as displayed below.

Can I use local storage in ionic?

That's one of the biggest arguments in favour of Ionic Storage; Ionic Storage will automatically select the best possible underlying storage engine available on the current platform. Normally this means IndexedDB or otherwise localstorage.

How do you display an array in ionic?

To display the list, you have to loop over the items in the array. Because your output is an array in an array, you can start the loop from the first element of the outer array. this. items[0] takes you to the first element in the outer array.


1 Answers

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

like image 90
abdoutelb Avatar answered Sep 28 '22 15:09

abdoutelb