【发布时间】:2018-07-21 04:45:27
【问题描述】:
我在 Ionic 3 App 中使用 SqlLite 原生插件。 根据 documentation ,它按预期工作。 在 app.commponent.ts 中,我创建了这样的表:
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));;
});
在 Home.ts pages 构造函数中,我是这样使用的
this.sqlite.create({
name: 'sdt.db',
location: 'default'
})
.then((db) => {
this.db = db;
});
在页面中:
ionViewDidLoad() {
this.loader = this.loading.create({
content: 'Loading ...',
cssClass: "loadingControllerCustomCss"
});
this.loader.present().then(() => {
this.getBalance();
});
}
详细方法是
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));
}
但我想创建一次表并重用 getBalance() 方法,这样我就不必重复代码段.因此,我想使用提供者(例如BackendService)作为服务方法,它可以被所有页面重用。
最佳做法是什么?
任何人都可以提供一个作为 Ionic 3 中提供程序的 sqlite 本机插件的完整示例,其中将显示打开数据库、创建模式和获取数据?
提前致谢!
【问题讨论】:
-
请在此处分享实际代码,否则假设太多;(需要 app.module.ts(这是您将初始化提供程序的地方),app.component.ts,您希望提供程序提供的页面被使用。
-
我已经分享了所有代码。我想在任何页面中使用提供程序。
标签: angular sqlite ionic2 ionic3 ionic2-providers