解决方法
1)首先,导航到项目的根文件夹并添加插件:
$ionic plugin add cordova-sqlite-storage $npm install --save @ionic-native/sqlite
2)在项目中创建一个新的提供者(在这个例子中,称为sqlStorage):
$ionic g provider sqlStorage
3)我想在app.component.ts中添加导入以在启动时初始化插件,而不是强制:
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); }); } /** * Perform an arbitrary sql operation on the database. Use this method * to have full control over the underlying database through sql operations * like SELECT,INSERT,and UPDATE. * * @param {string} query the query to run * @param {array} params the additional params to use for query placeholders * @return {Promise} that resolves or rejects with an object of the form * { tx: Transaction,res: Result (or 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 }),err: any) => reject({ tx: tx,err: err })); },(err: any) => reject({ err: err })); } catch (err) { reject({ err: err }); } }); } /** GET the value in the database identified by the given key. */ 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 the value in the database for the given key. */ set(key: string,value: string): Promise<any> { return this.query('insert into kv(key,value) values (?,?)',[key,value]); } /** REMOVE the value in the database for the given key. */ 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) { // this.sqlStorage.query(...); // this.sqlStorage.get(key).then(data => { // console.log(data); // } //... } }
信用:https://github.com/NickStemerdink有一些个人变化.
希望它会有所帮助并且工作得很好:)
编辑:仍然适用于Ionic v3.0.1(2017-04-06)