Ionic 2+ Storage Tutorial (With Example) -- Words (608)

Ionic
Ionic 2+ Storage Tutorial (With Example)

This tutorial will cover how to use Ionic 2+ (also Ionic 3) local/native storage to easily store and persist key-value pairs and JSON objects. Ionic Storage abstracts all available mechansims for data storage such as native Cordova SQLite and browser storage APIs like IndexedDB, WebSQL or localStorage. The most suitable way will be automatically chosen depending on your use case or more precisely the underlying platform , for example for native apps running on mobile devices SQLite will be used for storage but for progressive web apps running on the browser platform, where there is no native storage, either localStorage or IndexedDB will be used.

Getting started

First of all, before you can use SQLite as a storage option for native apps, you'll need to install the Cordova plugin for SQLite using the following command:

ionic cordova plugin add cordova-sqlite-storage

Next you need to install the Storage package for older Ionic versions before v2.

npm install --save @ionic/storage

Next just like any module you need to add to the list of imports in src/app/app.module.ts

import { IonicStorageModule } from '@ionic/storage';
/* ... */    
@NgModule({
  /* ... */
  imports: [      
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  /* ... */
})
export class AppModule {}

Now you are ready to use the Storge API in any component by simply injecting it via component constructor. So lets create a full demo showing how you can use Storage API inside an Ionic 2+ (or Ionic 3) application (either native app or progressive web app).

Create an Ionic 2+ (Ionic 3) Project

Open your terminal or command prompt then create an Ionic 3 project using the following command:

ionic start ionic-storage-example blank 

This will generate a new project based on the blank template which has only on default home page (which is sufficient for our example demo).

Next navigate inside your project directory then open it with your favorite code editor (Did you try VSCode? it's a nice IDE by Microsoft with powerful TypeScript support).

First follow the installation instructions on the Get Started section above.

Next open src/pages/home/home.ts then import and inject Storage class:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
/* ... */
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController,public storage: Storage) {}
}

Now lets say we want to persist some app settings such as color. We can do that using the Storage class APIs: get and set:

  public set(settingName,value){
    return this.storage.set(`setting:${ settingName }`,value);
  }
  public async get(settingName){
    return await this.storage.get(`setting:${ settingName }`);
  }
  public async remove(settingName){
    return await this.storage.remove(`setting:${ settingName }`);
  }
  public clear() {
    this.storage.clear().then(() => {
      console.log('all keys cleared');
    });
  }

Please note that these methods return Promises. Also for the sake of this simple example we place these methods on the component but normally this kind of logic should be placed inside services.

Next lets add some buttons to trigger these methods:

Open src/pages/home/home.html then add:

<ion-content padding>
  <button ion-button (click)="set('color','blue')">Set Color To Blue</button>
  <button ion-button (click)="remove('color')">Remove Color Setting</button>
</ion-content>

Values can be simple values such as strings and numbers or complex JSON objects.

This is all for this tutorial where we have seen how to use Ionic 2+ Storage class to persist key-value pairs and JSON objects. For advanced CRUD you may want to consider using Ionic Native SQLite or PouchDB.



mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.