I am using SqLite native plugin in Ionic 3 App. As per documentation , it works as expected. In app.commponent.ts , I created the table like this:
this.sqlite.create({
name: 'sdt.db',
location: 'default'
})
.then((db) => {
//create table if not exists!!!
this.db = db;
console.log(" within app components");
var createTableAccount = "CREATE TABLE IF NOT EXISTS 'accounts' ( 'accountid' INTEGER, 'accountName' TEXT NOT NULL, 'remarks' TEXT, 'initBalance' INTEGER NOT NULL, PRIMARY KEY('accountid') );"
this.db.transaction(function(tx) {
tx.executeSql(createTableAccount);
//todo: create a transaction table .........
//todo: insert data to table
}).then(() => {
console.log("basic structure sql executed")
//this.presentToast();
}).catch(e => console.log(e));;
});
In Home.ts pages constructor, I have used like this
this.sqlite.create({
name: 'sdt.db',
location: 'default'
})
.then((db) => {
this.db = db;
});
in pages:
ionViewDidLoad() {
this.loader = this.loading.create({
content: 'Loading ...',
cssClass: "loadingControllerCustomCss"
});
this.loader.present().then(() => {
this.getBalance();
});
}
detail method is
getBalance() {
var balanceQuery = "select sum(trxamount) sumofamount from transactiontable";
this.db.executeSql(balanceQuery, [])
.then((data) => {
this.balance = data.rows.item(0).sumofamount;
}
)
.catch(e => console.log(e));
}
But I want to create table once and reuse the getBalance() method so that I don't have to repeat segment of code.Hence, I want to use a provider(example BackendService) as a service method which can be reusable to all pages.
What will be the best practice ?
Can any body help with a complete example of sqlite native plugin as a provider in Ionic 3 where open database,create schema and get data will be shown?
Thanks in advanace!