1) First of all, go to the root folder of your project and add the plugin:
$ ionic plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
2) Create a new provider inside the project (in this example called SqlStorage ):
$ ionic g provider sqlStorage
3) I would like to add the import to app.component.ts in order to initialize the plugin at startup, and not required:
import {SqlStorage} from '../providers/sql-storage';
...
...
constructor(public sqlStorage: SqlStorage){}
4) app.module.ts, :
import { SQLite } from '@ionic-native/sqlite';
import { SqlStorage } from '../providers/sql-storage';
...
...
providers: [SQLite, SqlStorage]
5) sql-storage.ts:
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Injectable()
export class SqlStorage {
storage: any;
DB_NAME: string = '__ionicstorage';
constructor(public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
this.storage = db;
this.tryInit();
});
});
}
tryInit() {
this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.storage.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
} catch (err) {
reject({ err: err });
}
});
}
get(key: string): Promise<any> {
return this.query('select key, value from kv where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
set(key: string, value: string): Promise<any> {
return this.query('insert into kv(key, value) values (?, ?)', [key, value]);
}
remove(key: string): Promise<any> {
return this.query('delete from kv where key = ?', [key]);
}
}
6) .ts:
import {SqlStorage} from '../../providers/sql-storage';
export class ExamplePage {
constructor(public sqlStorage: SqlStorage) {
}
}
: https://github.com/NickStemerdink .
, :)
EDIT: Ionic v3.0.1 (2017-04-06)