SQLiteObject在离子3中未定义



我正在使用Ionic-Native SQLite数据库进行离子应用程序,并且在浏览器中进行测试,我正在使用WebSQL。在浏览器中运行良好,但是在Android设备中运行应用程序时。它给我带来的错误,例如Cannot read property 'transaction' of undefined。以下是供参考的代码。

1(dbprovider.ts

import { Platform } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
declare var window: any;
@Injectable()
export class DBProvider {
    DB_NAME: string = 'DailySheet.db';
    public websql = null;
    public sqlite: SQLite;
    sqliteobj: any;
    public AppUsers = [];
    constructor(public platform: Platform) {
        if (this.platform.is('core')) {
            this.websql = window.openDatabase(this.DB_NAME, "1.0", "Test DB", 2 * 1024 * 1024);
            console.log('Database opened.');
            this.createTable();
        }
        this.platform.ready().then(() => {
            if (!this.platform.is('core')) {
                this.sqlite.create({ name: this.DB_NAME, location: 'default' })
                    .then((db: SQLiteObject) => {
                        console.log('Database opened.');
                        this.sqliteobj = db;
                        this.createTable();
                    });
            }
        });
    }
    createTable() {
        this.query(`CREATE TABLE IF NOT EXISTS AppUser (
                         UserId INTEGER NOT NULL,
                         MobileNo   TEXT NOT NULL UNIQUE,
                         Email  TEXT,
                         PRIMARY KEY(UserId)
                     )`)
            .then(data => {
                console.log('Table created.');
            })
            .catch(err => {
                console.error('Unable to create initial storage tables', err.tx, err.err);
            });
    }
    getAppUsers(): Promise<any> {
        let query = 'SELECT * FROM AppUser';
        return this.query(query)
            .then(data => {
                if (data.res.rows.length > 0) {
                    console.log('Rows found.');
                    return data.res.rows;
                }
                else {
                    console.log('No rows found.');
                }
            });
    }
    insertAppUser(): Promise<any> {
        let id = 1;
        let mobileno = '8905606191';
        let email = 'niravparsana94@gmail.com';
        return this.query('INSERT INTO AppUser (UserId, MobileNo, Email) VALUES (' + id + ' ,"' + mobileno + '" ,"' + email + '")')
            .then(data => {
                console.log('Insert success.');
                return data;
            })
            .catch(err => {
                console.error('Unable to insert', err.tx, err.err);
            });
    }
    updateAppUser(UserId): Promise<any> {
        let query = "UPDATE Todo SET Email=? WHERE UserId=?";
        return this.query(query, ['niravparsana@outlook.com', UserId])
            .then(data => {
                console.log('AppUser Updated.');
                return data;
            })
            .catch(err => {
                console.error('Unable to update', err.tx, err.err);
            });
    }
    deleteAppUser(UserId): Promise<any> {
        let query = "DELETE FROM AppUser WHERE UserId=?";
        return this.query(query, [UserId])
            .then(data => {
                return data;
            })
            .catch(err => {
                console.error('Unable to delete', err.tx, err.err);
            });
    }
    query(query: string, params: any[] = []): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                if (this.platform.is('core')) {
                    this.websql.transaction((tx: any) => {
                        tx.executeSql(query, params,
                            (tx: any, res: any) => resolve({ tx: tx, res: res }),
                            (tx: any, err: any) => reject({ tx: tx, err: err }));
                    },
                        (err: any) => reject({ err: err }));
                }
                else {
                    this.sqliteobj.transaction((tx: any) => {
                        tx.executeSql(query, params,
                            (tx: any, res: any) => resolve({ tx: tx, res: res }),
                            (tx: any, err: any) => reject({ tx: tx, err: err }));
                    },
                        (err: any) => reject({ err: err }));
                }
            } catch (err) {
                reject({ err: err });
            }
        });
    }
}

2(home.ts

import { Component, OnInit } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { DBProvider } from '../../providers/DBProvider';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit {
  AppUsers: Array<Object>;
  constructor(public navCtrl: NavController, private platform: Platform, public db: DBProvider) {
  }
  ionViewDidLoad() {
    this.deleteAppUser();
    this.insertAppUser();
    this.getAllAppUsers();
  }
  ngOnInit() {
  }
  public deleteAppUser() {
    this.db.deleteAppUser(1)
      .then(data => {
        if (data.res.rowsAffected == 1) {
          console.log('AppUser Deleted.');
        }
        else {
          console.log('No AppUser Deleted.');
        }
      })
      .catch(ex => {
        console.log(ex);
      });
  }
  public insertAppUser() {
    this.db.insertAppUser()
      .then(data => {
      })
      .catch(ex => {
        console.log(ex);
      });
  }
  public getAllAppUsers() {
    this.db.getAppUsers()
      .then(data => {
        this.AppUsers = data;
      })
      .catch(ex => {
        console.log(ex);
      });
  }
}

在调试时,我在某种程度上发现了代码在浏览器和移动设备中以差异顺序运行。

在浏览器中

  1. dbprovider构造函数
  2. this.createtable((函数(dbprovider.ts(
  3. this.deleteappuser((函数(home.ts(
  4. this.insertappuser((函数(home.ts(
  5. this.getAlpusers((函数(home.ts(

在Android设备中

  1. dbprovider构造函数
  2. this.deleteappuser((函数(home.ts(
  3. this.insertappuser((函数(home.ts(
  4. this.getAlpusers((函数(home.ts(
  5. this.createtable((函数(dbprovider.ts(

您可能会在dbprovider构造函数中分配。但是,尽管调试我发现home.ts的函数在此之前都在调用。sqliteObj被分配了,这就是为什么它给出像 Cannot read property 'transaction' of undefined这样的错误。但是问题是为什么在此之前从home.ts召唤函数。

据我所知,您需要在SQLITE数据库上的每个呼叫中需要this.sqlite.create(...。因此,您必须在sqliteObj之前将其包括在查询功能中。

相关内容

  • 没有找到相关文章

最新更新