[英]How to use database method ( Sqlite plugin) as a Provider in Ionic 3?
I am using SqLite native plugin in Ionic 3 App . 我在Ionic 3 App中使用SqLite本机插件。 As per documentation , it works as expected.
根据文档 ,它按预期工作。 In app.commponent.ts , I created the table like this:
在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));;
});
In Home.ts pages constructor, I have used like this 在Home.ts 页面构造函数中,我已经使用过
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. 但是我想一次创建表并重用 getBalance()方法,这样我就不必重复代码段。因此,我想使用provider(例如BackendService )作为服务方法,该方法可以在所有页面上重复使用。
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? 作为Ionic 3中提供程序的sqlite本机插件的完整示例,任何机构都可以帮忙吗,其中将显示打开数据库,创建架构和获取数据?
Thanks in advanace! 谢谢先进!
OK first you need to install native plugins, see instructions here: https://ionicframework.com/docs/native/sqlite/ 首先,您需要安装本机插件,请参见此处的说明: https : //ionicframework.com/docs/native/sqlite/
once done create your sqlite provider. 完成后,创建您的sqlite提供程序。 Normally inside src you do folder "providers" and add sqlite.ts.
通常,在src内,您要文件夹“ providers”并添加sqlite.ts。
Its contents: 其内容:
import { Injectable } from '@angular/core'; import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; @Injectable() export class SqLiteProvider { // we need to declare a var that will point to the initialized db: public db: SQLiteObject; constructor( private sqlite: SQLite ) { this.sqlite.create({ name: 'data.db', location: 'default' }).then((db: SQLiteObject) => { // here we will assign created db to our var db (see above) this.db = db; // we can now create the table this way: this.db.executeSql('create table danceMoves(name VARCHAR(32))', {}) .then(() => console.log('Executed SQL')) .catch(e => console.log(e)); }).catch(e => console.log(e)); } // here in this provider we create getBalance method, that should be accessible by other pages: getBalance() { // we will do Promise here: return new Promise((resolve, reject) => { let balanceQuery = "select sum(trxamount) sumofamount from transactiontable"; this.db.executeSql(balanceQuery, []).then((data) => { let balance = data.rows.item(0).sumofamount; // if we successfully obtain data - we resolve it, means it can be available via callback resolve(balance) }).catch((err)=>{ console.log(err); reject(err)}) // we deal with errors etc }) } }
Then you need to make this "global scope" provider if you want to use it anywhere in your app. 然后,如果要在应用程序中的任何位置使用它,则需要创建此“全局范围”提供程序。 For that you go to app.module.ts and import:
为此,请转到app.module.ts并导入:
import { SqLiteProvider } from '../../providers/sqlite'; 从“ ../../providers/sqlite”导入{SqLiteProvider}; // ensure this is the folder where you created your sqlite.ts
//确保这是您创建sqlite.ts的文件夹
Now for any page/component if you need to use this provider you just: - import it, - then use constructor to initialize it. 现在,对于任何页面/组件,如果您需要使用此提供程序,则只需:-导入它,-然后使用构造函数对其进行初始化。
// some page or component: //一些页面或组件:
import { SqLiteProvider } from '../../providers/sqlite' ... constructor( private sqlProvider: SqLiteProvider ) {} 从'../../providers/sqlite'...构造器导入{SqLiteProvider}(私有sqlProvider:SqLiteProvider){}
Now in this page you can access this provider's methods by doing 现在,在此页面中,您可以通过以下方式访问此提供程序的方法
this.sqlProvider.getBalance().then((data)=>{ console.log(data)}). this.sqlProvider.getBalance()。then((data)=> {console.log(data)})。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.