Ionic2 arrays in local storage


#1

In ionic2, what is the best way to work with arrays in LocalStorage?

I used to use ngStorage - can this still work and if so, how to import and use it in Ionic2?
I’ve tried: import {StorageService} from ‘ngStorage’; with no luck.

I can use import {Storage} from ‘ionic-angular’; but am hearing it is not so convenient for arrays.

Also, not sure if angular-local-storage works with Ionic2 or not. I am having no luck.

Any advice appreciated.


Ionic 2 storage string, get a strange string
#2

You can use either LocalStorage or SqlStorage (preferred) with Ionic 2. You can store arrays fine, you need to store it as a JSON string though and when you retrieve the data from storage you can convert that JSON string back into an array.


#3

Hi Josh,
I see so many examples of Storage, LocalStorage, ngStorage but having no luck getting them to work in Ionic2.
I was working with ngStorage in Ionic1 which was great as I did not need convert to JSON and back. But I see no signs it works in Ionic2.

When you refer LocalStorage, is it imported from ‘ionic-angular’ ?

I have tried:
this.local = new LocalStorage(Storage);
this.local.set(‘visited’, ‘true’);
and this.local.get('visited) but it returns an object with nothing in it.
A small example would be great or a link to a working example in Ionic2.

I can get SqlStorage to work but just seemed like overkill to create tables for One array.
But, I can fall back to it.


#4

Here’s an example I’m using (make sure to import both Storage and LocalStorage):

    this.local = new Storage(LocalStorage);

    this.local.get('introShown').then((result) => {
      if(result){
        this.rootPage = HomePage;
      } else {
        this.local.set('introShown', true);
        this.rootPage = IntroPage;
      }
    });

It’s best to use SqlStorage for most things though, you can use SqlStorage in the same way as LocalStorage (as a simple key-value storage system), you don’t need to use tables and such.


#5

Hey Josh - Thanks a bunch. Both for the example and the tip on SqlStorage.
I am just getting started with Ionic2 and you really helped, cheers.


#6

Hi guys, I have an issue with the localStorage… The promise returns a undefined value.

dataBase.get(‘entities’).then(function(entities){
console.debug(entities);
},function(e){
console.error(e);
})
Promise {_promise: Object}
undefined

As you can see, console.debug(entities) prints undefined!.. so I dont know what the problem is. Sometimes this does not happen…