Can't get data from cordova sqlite


#1

What I simply try to do is getting data back from sqlite db.

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

@Component({
  selector: 'page-messages',
  templateUrl: 'messages.html'
})
export class MessagesPage {
  selectedItem: any;
  messages: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private sqlite: SQLite) {
    this.selectedItem = navParams.get('item');
    this.messages = [];
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    })
    .then((db: SQLiteObject) => {
      console.log('SELECT * FROM message');
      db.executeSql('SELECT * FROM message', {})
        .then(function(data) {
          for(let i = 0; i < data.rows.length; i++) {
            let id = data.rows.item(i).id;
            let message_to = data.rows.item(i).message_to;
            let message_text = data.rows.item(i).message_text;
            this.messages.push({
                id: id,
                message_to: message_to,
                message_text: message_text
            });
          }
        })
        .catch(e => console.log(JSON.stringify(e))); // ERROR HERE
    })
    .catch(e => console.log(JSON.stringify(e)));
  }
}

Now i get an error in my first catch:

{"__zone_symbol__currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}}

I can’t really understand whats going on about that execution.
Where i’m going wrong?
Thank you for help.


#2

Alright. Two things.
So you almost never want to type function inside an Ionic app. Instead, you want to utilize the fat arrows syntax () =>.
Secondly, Promise nesting is an anti-pattern and should be avoided.

That being said, here’s what I’d suggest:

this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
.then((db: SQLiteObject) => {
  console.log('SELECT * FROM message');
  return db.executeSql('SELECT * FROM message', {});
})
.then((data) => {
  for(let i = 0; i < data.rows.length; i++) {
    let id = data.rows.item(i).id;
    let message_to = data.rows.item(i).message_to;
    let message_text = data.rows.item(i).message_text;
    this.messages.push({
        id: id,
        message_to: message_to,
        message_text: message_text
    });
  }
})
.catch(e => console.log(e));