我做了什么:
- 今天安装了离子,通过命令
npm install -g ionic
并对cordova集成说'y'。 - 安装科尔多瓦:
npm install -g cordova
- 创建了一个新项目:
ionic start sqlite3demo blank
安装的 Ionic 本机存储:
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
现在是代码。我像这样SQLite
导入app.module.ts
:
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { SQLite } from '@ionic-native/sqlite';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
SQLite
]
})
export class AppModule {}
然后,我像这样修改了默认主页:
<ion-header>
<ion-navbar>
<ion-title>
SQLite demo
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-content>
<button ion-button (click)="createTables()">Create db</button>
<p>Result: {{ message }}</p>
</ion-content>
</ion-content>
最后,我home.ts
这样修改:
import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
message = '';
db: SQLiteObject;
constructor(private platform: Platform, public navCtrl: NavController, private sqlite: SQLite) {
this.platform.ready().then(() => {
this.sqlite.create({
name: 'todos.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.message = JSON.stringify(db);
this.db = db;
});
});
}
public createTables() {
return this.db.executeSql(
`CREATE TABLE IF NOT EXISTS list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
);`)
.then(() => this.message = 'OK')
.catch((err) => this.message = "error detected creating tables -> " + JSON.stringify(err));
}
}
毕竟,我执行ionic cordova run android
,我可以从 中看到 JSON db
,但在那之后,我单击按钮创建一个表,而不是看到“确定”,而是从错误中看到 JSON。
我做错了什么?为什么它不起作用?
编辑:我使用的版本是:
"@ionic-native/sqlite": "^4.12.2",
"cordova-sqlite-storage": "^2.4.0"