In this post, we will add Cordova’s SQLite storage plugin in Ionic version 4 Application. This is the commanly and widely used storage plugin by most of the Ionic developers since version 1 of Ionic. Storage is widely used to store personalized settings by the user in the application which is not required to be stored on server side.

Application developers sometimes need to save a bunch of information on the user side to control some features and provide some offline functionalities to application users, in that case, local storage proves very handy. Using Ionic’s Native storage plugin we can storage key value pairs which may have any type of data from a simple string or integers to JSON objects. But this locally stored data will remain until the application is Uninstalled or device is formatted.

LocalStorage engines are managed by the plugin itself according to OS on which application is installed or running like in Native app context Storage will be done using SQLite, which is one of the most stable and most preferred file-based storage databases. On Progressive Web Apps platform IndevedDB, WebSQL or localStorage is chosen in a defined order.

Let’s start implementation of Storage Plugin in Ionic 4 Application

Here we will start with a new application in Ionic version 4 which is now in beta phase but soon stable version will be available with minor installation step changes in commands to install.

Create a new Ionic 4 Application

Create a new application using Ionic CLI
To create an application you must have NodeJS and Ionic Cordova CLI

JavaScript

1

$npm install-gionic cordova

Run the following command to create a new application

JavaScript

1

2

$ionic start Ionic4NativeStorage blank--type=angular

$cd Ionic4NativeStorage

Install Cordova and Ionic Native Plugin

JavaScript

1

2

$ionic cordova plugin add cordova-sqlite-storage

$npm install--save@ionic/storage

Import declare plugin in Application’s module file

In the app.module.ts file, import plugin then adds in Imports array in NgModule. Replace below code:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import{NgModule}from'@angular/core';

import{BrowserModule}from'@angular/platform-browser';

import{RouteReuseStrategy}from'@angular/router';

import{IonicModule,IonicRouteStrategy}from'@ionic/angular';

import{SplashScreen}from'@ionic-native/splash-screen/ngx';

import{StatusBar}from'@ionic-native/status-bar/ngx';

import{AppComponent}from'./app.component';

import{AppRoutingModule}from'./app-routing.module';

import{IonicStorageModule}from'@ionic/storage';

@NgModule({

declarations:[AppComponent],

entryComponents:[],

imports:[

BrowserModule,

IonicModule.forRoot(),

AppRoutingModule,

IonicStorageModule.forRoot()

],

providers:[

StatusBar,

SplashScreen,

{provide:RouteReuseStrategy,useClass:IonicRouteStrategy}

],

bootstrap:[AppComponent]

})

exportclassAppModule{}

After adding the plugin to the app’s main module, we can now use Native Storage anywhere in the application. Here we will use it in the home component.

In the home.page.ts file, import plugin then creates an instance in component’s constructor.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import{Component}from'@angular/core';

import{Storage}from'@ionic/storage';

@Component({

selector:'app-home',

templateUrl:'home.page.html',

styleUrls:['home.page.scss'],

})

exportclassHomePage{

constructor(private storage:Storage){

// set a key/value

this.storage.set('name','Max');

// Or to get a key/value pair

this.storage.get('age').then((val)=>{

console.log('Your age is',val);

});

}

}

In the above code, we just simply setting and getting the string value.

Set a Value in a Key

set() : Set the value for the given key. Returns a promise that resolves when the key and value are set

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

// set a key/value

setValue(key:string,value:any){

this.storage.set(key,value).then((response)=>{

console.log('set'+key+' ',response);

//get Value Saved in key

this.getValue(key);

}).catch((error)=>{

console.log('set error for '+key+' ',error);

});

}

Get Value in a Key

get() : Get the value associated with the given key. Returns a promise with the value of the given key

JavaScript

1

2

3

4

5

6

7

8

9

10

// get a key/value pair

getValue(key:string){

this.storage.get(key).then((val)=>{

console.log('get '+key+' ',val);

this.data[key]="";

this.data[key]=val;

}).catch((error)=>{

console.log('get error for '+key+'',error);

});

}

Remove a key/value pair

remove() : Remove any value associated with this key. Returns a promise that resolves when the value is removed

JavaScript

1

2

3

4

5

6

7

8

9

// Remove a key/value pair

removeKey(key:string){

this.storage.remove(key).then(()=>{

console.log('removed '+key);

this.data[key]="";

}).catch((error)=>{

console.log('removed error for '+key+'',error);

});

}

Current Storage Engine Used

Get the name of the driver being used.

JavaScript

1

2

3

4

//Get Current Storage Engine Used

driverUsed(){

console.log("Driver Used: "+this.storage.driver);

}

Traverse key/value pairs

forEach() : Iterate through each key,value pair. Returns a promise that resolves when the iteration has finished.

JavaScript

1

2

3

4

5

6

7

traverseKeys(){

this.storage.forEach((value:any,key:string,iterationNumber:Number)=>{

console.log("key "+key);

console.log("iterationNumber "+iterationNumber);

console.log("value "+value);

});

}

All Stored Keys

keys() : Returns a promise that resolves with the keys in the store.

JavaScript

1

2

3

4

5

6

// Traverse key/value pairs

listKeys(){

this.storage.keys().then((k)=>{

console.table(k)

});

}

Total Keys Stored

length() : Returns a promise that resolves with the number of keys stored.

Leave a Reply

Connect with

I allow to create an account

When you login first time using a Social Login button, we collect your account public profile information shared by Social Login provider, based on your privacy settings. We also get your email address to automatically create an account for you in our website. Once your account is created, you'll be logged-in to this account.

DisagreeAgree

This comment form is under antispam protection

Connect with

I allow to create an account

When you login first time using a Social Login button, we collect your account public profile information shared by Social Login provider, based on your privacy settings. We also get your email address to automatically create an account for you in our website. Once your account is created, you'll be logged-in to this account.