Pavan Alapati Pavan Alapati - 3 years ago 113
AngularJS Question

TypeError: this.sqlites.executeSql is not a function

Hi we are creating on hybrid mobile app. We are trying to save data into

SQLite
using Ionic3 & Angular4. So we add plugin to our project then we tried like this:

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

}


In above code we are creating table in
constructor
it's working fine then we tried to insert data into table using save button action. But we are getting error ERROR

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


Please guide us. What do we miss?

Answer Source

Its because this.sqlites is of type SQLite. Which doesn't have a method executeSql. An SQLiteObject on the other hand does.

You should inject SQLite in the constructor:

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

    constructor(private sqlites: SQLite) {
    ...

You can store the SQLiteObject that is returned from this:

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

Then you can use it anywhere in your class, like in the save()-function:

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));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download