简体   繁体   中英

How to use database method ( Sqlite plugin) as a Provider in Ionic 3?

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!

OK first you need to install native plugins, see instructions here: https://ionicframework.com/docs/native/sqlite/

once done create your sqlite provider. Normally inside src you do folder "providers" and add 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:

import { SqLiteProvider } from '../../providers/sqlite'; // ensure this is the folder where you created your 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 ) {}

Now in this page you can access this provider's methods by doing

this.sqlProvider.getBalance().then((data)=>{ console.log(data)}).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM