This post is all about saving data locally in your cool new app. In this post, you will learn
- How to implement
cordova-sqlite-storage
in our app. - How to integrate
native-storage
into an ionic app.
Before start, first you will need an ionic app to start with, hence you can follow how to create an ionic app for beginners and start after that from here.
1. Storage — What and why?
Storage is an easy way to store key/value pairs and JSON objects. Storage uses a variety of storage engines underneath, picking the best one available depending on the platform.
When running in a native app context, Storage will prioritize using SQLite, as it’s one of the most stable and widely used file-based databases, and avoids some of the pitfalls of things like local storage and IndexedDB, such as the OS deciding to clear out such data in low disk-space situations.
As every application needs their data to store in local storage or cache for fast loading or for any purpose, we have a nice solution for that in ionic as @ionic/storage.
To start with first execute the following command in your terminal:
ionic cordova plugin add cordova-sqlite-storage
Next, install the package (comes by default for Ionic apps > Ionic V1):
npm install --save @ionic/storage
Next, add it to the imports list in your NgModule
declaration (for example, in src/app/app.module.ts
):
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
// ...
]
})
export class AppModule {}
Now create a service for ionic storage functions by executing this command:
ionic generate service storage
Now in your generated storage service add the following codes to use wherever needed in the application:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(public storage: Storage)
{ console.log('Your storage provider is working here !'); }
// set a key/value
async set(key: string, value: any): Promise<any> {
try {
const result = await this.storage.set(key, value);
console.log('set string in storage: ' + result);
return true;
} catch (reason) {
console.log(reason);
return false;
}
}
// to get a key/value pair
async get(key: string): Promise<any> {
try {
const result = await this.storage.get(key);
console.log('storageGET: ' + key + ': ' + result);
if (result != null) {
return result;
}
return null;
} catch (reason) {
console.log(reason);
return null;
}
}
// set a key/value object
async setObject(key: string, object: Object) {
try {
const result = await this.storage.set(key, JSON.stringify(object));
console.log('set Object in storage: ' + result);
return true;
} catch (reason) {
console.log(reason);
return false;
}
}
// get a key/value object
async getObject(key: string): Promise<any> {
try {
const result = await this.storage.get(key);
if (result != null) {
return JSON.parse(result);
}
return null;
} catch (reason) {
console.log(reason);
return null;
}
}
// remove a single key value:
remove(key: string) {
this.storage.remove(key);
}
// delete all data from your application:
clear()
{
this.storage.clear();
}
}
Now create a page using the ionic command:
ionic generate page storagedemo
In storagedemo.page.ts
inject storage
in constructor
constructor(public storageService: StorageService) { }
Now let’s save and get strings in your constructor. For simplicity, we’ll just output the result in the console.
i. Save String:
this.storageService
.set('user_name', 'Shadman').then(result => {
console.log('Data is saved');
}).catch(e => {
console.log("error: " + e);
});
ii. Get String:
this.storageService
.get('user_name').then(result => {
if (result != null) {
console.log('Username: '+ result);
}
}).catch(e => {
console.log('error: '+ e);
// Handle errors here
});
iii. Save an Object:
this.storageService
.setObject('person', {name : 'Shadman', age : 26});
iv. Get an Object:
this.storageService
.getObject('person').then(result => {
if (result != null) {
console.log('Person: '+ result);
}
}).catch(e => {
console.log('error: ', e);
});
v. You can remove any value associated with the key:
this.storageService.remove('user_name');
vi. You can delete/clear all the data from your application:
this.storageService.clear();
2. Ionic native-storage — What and Why?
This plugin is created because of the non-persistent property of LocalStorage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.
When to use the plugin:
- Simple: Uniform and convenient way of organizing, storing, and accessing the data
- Fast: Less than 1 millisecond to save or retrieve an object (in general)
- Persistence: Save data over multiple sessions, i.e. holds the data until the application is removed from the device
- Small data: Store small amounts of persistent data (less than a few hundred kilobytes)
- It is possible to store more than a few megabytes, but that’s not the intended usage of the plugin.
When not to use the plugin:
- Storing and retrieving files can be done by means of the file plugin
- For storing many objects please consider trying a database-based strategy, for instance: WebSQL and SQLite plugin.
Installation:
Execute the following command in your terminal:
ionic cordova plugin add cordova-plugin-nativestoragenpm install @ionic-native/native-storage
After installation completes, import NativeStorage
module in your app.module.ts
import { NativeStorage } from '@ionic/storage';
@NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
NativeStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
// ...
]
})
export class AppModule {}
Now you are totally set to use this in your app’s components/pages as:
Storing values
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
Retrieving values
this.nativeStorage.getItem('myitem')
.then(
data => console.log(data),
error => console.error(error)
);
Retrieving all keys
storageService.keys().then(
data => console.log(data),
error =>{console.log(error);}
);
Removing values
Removing a single variable:
NativeStorage.remove("reference_to_value",<success-callback>, <error-callback>);
Removing all stored variables:
NativeStorage.clear(<success-callback>, <error-callback>);
iOS-specific features
- App Groups (share data between apps) First the suite name must be provided before accessing and retrieving data.
NativeStorage.initWithSuiteName("suitename");
Now at last but not least, you’re all set to play with ionic/storage and ionic/native storage.
Conclusion:
In this post, we learned how to implement ionic SQLite-storage and ionic native-storage, we got to know the difference and the use of these two in ionic 4 application. I hope this post made your confusions clear that what is ionic-storage and why to use, as same for the native-storage.
NEED FREE IONIC 4 STARTERS?
You can also find free Ionic 4 starters on our website enappd.com
You can also make your next awesome app using Ionic 4 Full App
Next Steps
Now that you have learned the implementation of SQLite-storage and native -storage for storing or caching values in Ionic 4, you can also try
- Play Spotify style mucic in ionic 4.
- Ionic 4 PayPal payment integration — for Apps and PWA
- Ionic 4 Apple Pay integration
- Twitter login in Ionic 4 with Firebase
- Facebook login in Ionic 4 with Firebase
- How to implement google vision in Ionic 4
- QR Code and scanners in Ionic 4 and
- Translations in Ionic 4
Top comments (0)