TypeError: this.sqlites.executeSql is not a function

TypeError: this.sqlites.executeSql is not a function

您好,我们正在创建混合移动应用程序。我们正在尝试使用 Ionic3 和 Angular4 将数据保存到 SQLite。所以我们将插件添加到我们的项目然后我们尝试这样:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
    sqlites:any = null;
    constructor(public navCtrl: NavController,public plt: Platform) {
        this.sqlites = new SQLite();

        this.plt.ready().then((readySource) => {
        this.sqlites.create({
            name: 'userInfo.db',
            location: 'default'
        })
        .then((db: SQLiteObject) => {
            db.executeSql('CREATE TABLE IF NOT EXISTS usernameList(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age NUMBER,address TEXT,education TEXT)', {})
            .then(() => alert('Executed SQL'))
            .catch(e => console.log(e));
        })
        .catch(e => console.log(e));
    });

}


    user = {};

    save(user){
        this.sqlites.executeSql('INSERT INTO usernameList(name,age,address,education) VALUES(?,?,?,?)', [user.username,user.age,user.address,user.education])
        .then(()=>alert("insertFine"))
        .catch(e => console.log(e));
    }

}

在上面的代码中,我们在 constructor 中创建了 table 它工作正常,然后我们尝试使用保存按钮操作将数据插入 table。但是我们收到错误 ERROR

TypeError: this.sqlites.executeSql is not a function. (In 'this.sqlites.executeSql', 'this.sqlites.executeSql' is undefined) — main.js:183

请指导我们。我们错过了什么?

因为this.sqlitesSQLite类型。其中没有方法 executeSql。另一方面,SQLiteObject 会。

你应该在构造函数中注入 SQLite:

export class HomePage {
    // If you inject SQLite in the constructor you dont have to declare sqlites 
    // here
    // sqlites:any = null;

    constructor(private sqlites: SQLite) {
    ...

您可以存储由此返回的 SQLiteObject

this.sqlites.create({
    name: 'userInfo.db',
    location: 'default'
})
.then((db: SQLiteObject) => {
    this.db = db;
    ...
}

然后你可以在你的 class 中的任何地方使用它,就像在 save()- 函数中一样:

save(user){
    this.db.executeSql('INSERT INTO usernameList(name,age,address,education) VALUES(?,?,?,?)', [user.username,user.age,user.address,user.education])
    .then(()=>alert("insertFine"))
    .catch(e => console.log(e));
}