TypeError:this.sqlites.executeSql不是函数

时间:2017-07-25 08:16:05

标签: angular sqlite cordova ionic3

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

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中创建了表,它正常工作,然后我们尝试使用保存按钮操作将数据插入表中。但是我们收到错误ERROR

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

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

1 个答案:

答案 0 :(得分:2)

因为this.sqlites的类型为SQLite。哪个没有方法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;
    ...
}

然后你可以在课堂的任何地方使用它,比如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));
}