I an ionic program that uses sqlite to store data. When i return the data to the view, it returns nothing.
I have a service set up to fetch the data. It looks like
read(){
this.sqlite.create({
name: DB_NAME,
location: 'default'
})
.then((db: SQLiteObject) => {
db.executeSql('CREATE TABLE IF NOT EXISTS todos(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32), datetime VARCHAR(32))', {})
.then(() => console.log("Created Table OR NOT"))
.catch(e => this.presentAlert(e));
db.executeSql('SELECT * FROM todos ORDER BY id DESC', {})
.then((response) => {
if(response.rows.length > 0){
for(var i=0; i < response.rows.length; i++){
this.my_todos.push({
id:response.rows.item(i).id,
name:response.rows.item(i).name,
datetime:response.rows.item(i).datetime
})
}
}
//this.presentAlert(JSON.stringify(this.my_todos));
return this.my_todos;
})
.catch(e => this.presentAlert(JSON.stringify(e)));
})
.catch(e => this.presentAlert(JSON.stringify(e)));
}
On the home.ts file, i try to access the service like
this.todos = this.todoService.read()
When i log this.todos
on my console. It doesn't return anything. Can anyone please help me?...
//Hi, //You cannot do this this.todos = this.todoService.read(). //You should write promises to get data from sqlite and use them in your //component. //I expect read function is in the service file(todoService.ts). Change it like //this.
//Hi,
//You cannot do this this.todos = this.todoService.read().
//You should write promises to get data from sqlite and use them in your //component.
//I expect read function is in the service file(todoService.ts). Change it like //this.
public read() {
return new Promise((resolve,reject) => {
var db = new SQLite();
var query = "CREATE TABLE IF NOT EXISTS todos(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32), datetime VARCHAR(32))";
db.create({
name: "data.db",
location: "default"
}).then((db1: SQLiteObject) => {
db1.executeSql(query,[])
.then((res) => {
let todos = [];
if(res.rows.length > 0 ) {
todos.push(res.rows.item(0))
}
resolve(todos)
},(error) => {
reject(error);
});
})
}
// The promise returns an array of objects
In the page component
// declare this
public itemList : Array<Object>;
// In the constructor
this.itemList = [];
this.todoService.read().then((result) => {
this.itemList = <Array<Object>> result;
// you will get the retrieved data from sqlite from this array
console.log(this.itemList)
})
)
// This should work Please update me in case of any issues