What I have done:
npm install -g ionic
and saying 'y' to the cordova integration.npm install -g cordova
ionic start sqlite3demo blank
Installed Ionic native storage:
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic-native/sqlite
Now for the code. I imported SQLite
into app.module.ts
like this:
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 {}
And then, I modified the default home page like this:
<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>
And finally, I modified home.ts
like this:
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));
}
}
After all that, I execute ionic cordova run android
, and I can see the JSON from db
, but after that, I click the button to create a table and instead of seeing 'OK', I see the JSON from the error.
What did I do wrong? Why isn't it working?
EDIT: The versions I'm using are:
"@ionic-native/sqlite": "^4.12.2",
"cordova-sqlite-storage": "^2.4.0"
Finally, as it's described here, the documentation was obsolete. The way executeSql()
works is passing a []
as second parameter. It seems that Ionic Native team doesn't consider updating their documentation too much. There are other plugins with obsolete documentation too, like email composer
, making developers wasting many hours on things that have solution already.