SQLite not ready


#1

Hi, I’ve got the following problem:
I implemented a SQLite database provider that opens the database and holds the database-object.
The database is opened in the constructor:

constructor(public sqlite: SQLite, platform:Platform) {
    platform.ready().then(() => {
      this.sqlite.create({
        name: 'data.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        this.isInit = true;
        this.db = db;
      }).catch((e) => {
        console.log("error initConnection", e);
      });
    });
  }

Whenever I need the database object I simply can access it via the provider. So I do in my home.ts


ionViewDidEnter() {
    this.platform.ready().then((readySource) => {
      this.dbProvider.db.executeSql("SELECT COUNT(*) FROM library", []).then((countResult) => {
       this.libraryPages = countResult.rows.item(0)/this.limit;
     }).catch(e=> console.error(e));
        this.getElements();
    });
  }

Now there’s one problem: In dev mode everything works fine, but in prod-mode the database is not opened fast enough so my requests will result in

Uncaught (in promise): TypeError: Cannot read property ‘executeSql’ of undefined

I’ve tried to implement a getter for the db object that checks if the db object is not null and if so, open the database but it doesn’t work because opening the database is asynchronous and throwing a promise out of a promise seams to be an anti pattern as I’ve read it.

My app uses the database on multiple locations so I need it persistent. I’ve seen some suggestions that always open a new connection and other things but that’s not as dry as I expect a angular2 solution.

Do you know a way for that? Thank you.


#2

I tried using a settimeout in my v1 app. I tried to execute the opening in app.js under platform ready and use 300 ms delay in the enter event of the page.


#3

Chaining promises is just fine, though.

class DBProvider {
  ready: Promise<void>;
  constructor(plat: Platform, sqlite: SQLite) {
    this.ready = plat.ready().then(() => this.sqlite.create({
        name: 'data.db',
        location: 'default'
      }));
  }
}

ionViewDidEnter() {
  this.dbProvider.ready.then(() => {
    // db is reliably created here
  });
}

setTimeout() should not be used or recommended in Angular apps.