簡體   English   中英

如何在Ionic 3中使用數據庫方法(Sqlite插件)作為提供程序?

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

我在Ionic 3 App中使用SqLite本機插件。 根據文檔 ,它按預期工作。 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 頁面構造函數中,我已經使用過

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()方法,這樣我就不必重復代碼段。因此,我想使用provider(例如BackendService )作為服務方法,該方法可以在所有頁面上重復使用。

最佳做法是什么?

作為Ionic 3提供程序的sqlite本機插件完整示例,任何機構都可以幫忙嗎,其中將顯示打開數據庫,創建架構和獲取數據?

謝謝先進!

首先,您需要安裝本機插件,請參見此處的說明: https : //ionicframework.com/docs/native/sqlite/

完成后,創建您的sqlite提供程序。 通常,在src內,您要文件夾“ providers”並添加sqlite.ts。

其內容:

 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 }) } } 

然后,如果要在應用程序中的任何位置使用它,則需要創建此“全局范圍”提供程序。 為此,請轉到app.module.ts並導入:

從“ ../../providers/sqlite”導入{SqLiteProvider}; //確保這是您創建sqlite.ts的文件夾

現在,對於任何頁面/組件,如果您需要使用此提供程序,則只需:-導入它,-然后使用構造函數對其進行初始化。

//一些頁面或組件:

從'../../providers/sqlite'...構造器導入{SqLiteProvider}(私有sqlProvider:SqLiteProvider){}

現在,在此頁面中,您可以通過以下方式訪問此提供程序的方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM