
Storage in ionic 2 can be used to store data key/value pairs. We can also store JSON Objects. This Storage can work using may storage engines, here it will choose the best based on the platform. If the application runs in native platfrom it will use SQLite where as if it is in browser it uses IndexedDB or WebSQL. Follow the steps to use Storage
Install the cordova-sqlite-storage plugin:
cordova plugin add cordova-sqlite-storage --save
install "@ionic/storage" package (Optional for Ionic 2 >= RC.0):
npm install --save @ionic/storage // !important note: This is optional if you are using ionic 2 apps >= RC.0
Adding providers in NgModule:
Add the following line in /src/app/app.module.ts,
import { Storage } from '@ionic/storage'; export function provideStorage() { return new Storage(['sqlite', 'websql', 'indexeddb'], { name: 'database_name' }); } // Add "Storage" inside providers providers: [ { provide: Storage, useFactory: provideStorage }, Storage ]
Now your app.module.ts file will look like,
import { Storage } from '@ionic/storage'; // new line <-- export function provideStorage() { return new Storage(['sqlite', 'websql', 'indexeddb'], { name: 'database_name' }); } @NgModule({ declarations: [ ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ ], providers: [ { provide: Storage, useFactory: provideStorage }, Storage // new line <-- ] })
Use set() and get() methods to store and retrive data in your pages.
import { Storage } from '@ionic/storage'; export class MyApp { constructor(storage: Storage) { storage.set('key', 'value 1'); // store storage.get('name').then((val) => { // retrive console.log('Your value is', val); }) } }
Category:
Comments