I have been trying to incorperate sqlite into a simple Ionic app and this is the process I have been following:
ionic start myApp sidemenu
If someone still got an error when trying to run it in a browser, try this one:
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "my.db" }); //device
}else{
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
For later Ionic versions (Ionic 2+):
The best way to handle persistent storage with Ionic is using ionic-storage.
Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.
In your case for SQLite you need to first install the dependencies for both Angular and Cordova:
npm install @ionic/storage --save
and
cordova plugin add cordova-sqlite-storage --save
Then edit your NgModule declaration in src/app/app.module.ts
to add IonicStorageModule
as an import:
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [...],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['indexeddb', 'sqlite', 'websql'],
})
],
bootstrap: [...],
entryComponents: [...],
providers: [...],
})
export class AppModule { }
import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public storage: Storage) {}
}
Whenever you access storage, make sure to always wrap your code in the following:
storage.ready().then(() => { /* code here safely */});
storage.ready().then(() => {
storage.set('some key', 'some value');
});
storage.ready().then(() => {
storage.get('age').then((val: string) => {
console.log('Your age is', val);
});
});
storage.ready().then(() => {
storage.remove('key').then((key: string) => { /* do something after deletion */})
});
In Ionic 2, I am using the following code.
constructor(platform: Platform) {
platform.ready().then(() => {
if(platform.is("cordova")){
//USE Device
}
else {
//USE Browser
}
StatusBar.styleDefault();
});
So Turns out that it is because Cordova is platform specific and doesn't work when you run ionic serve
I was able to run the same code on an android device with out issue when I built and deployed.
you can replace the cordova plugin with window to use the websql databases
so instead of sqlitePlugin.openDatabase()
you can use window.openDatabase()