Ionic 2 RC0: SQLite errors due to loading timing

Hi there,
I’m not sure if the title is very clear, so I’ll try to explain my problem:

I’m using SQLite to save data in my app. I’ve wrapped it in an @Injectable to init DB structure, etc. This service contains the SQLite object connected to my database.
Database is initialized in platform.ready() to make sure the sqlite plugin is correctly loaded. My init function looks like this:

public init() {
  return this.db.openDatabase({
     name: 'openscore.db',
     location: 'default' // the location field is required
  }).then(() => {
      return this.initDbStructure();

This init is working as expected.

In my home page, I’m firing some queries but it always fails with TypeError: Cannot read property 'executeSql' of undefined
The undefined is the SQLite object of my service.

I’m pretty sure that the queries are fired before the DB has been initialized. If I add a timeout before executing the queries, everything work as expected. And if I keep using the app, all the future queries will be fine.

Those queries are fired inside a ionViewDidLoad. I tried different Lifecycles event, ngAfterViewInit but no more success.

This used to work fine on beta 11 with SQLStorage (now removed for good reasons, I’ve no problem with that :wink: )

How can I make sure my components are loaded when my app is totally ready and my DB initialized?

Thanks everybody! :slight_smile:

Hello Tdy,

I’m a newbie in ionic land and pretty new in web development (C# desktop apps in the past), but maybe I can help. I came upon your question by chance and I am also working on a database service for my app now. I wanted to give you this small tutorial: that I used and it helped me make it work.

I hope that will help you,

You might want to fire an event once the db is ready and then subscribe to that event in your component?

1 Like

Yes I thought about this solution. But, as it’s a fairly common usage so I was wondering if there was a more “built-in” way to do that.
And I don’t understand what it was working on beta 11 and not anymore on RC0. Maybe using NgModule has an impact on how the components are loaded, I don’t know enough how ngModule actually works to tell.

Thanks Bogdan. This blog is quite good and really helped me to get my app working. Unfortunately this article won’t help me in my current issue. :confused:

I doubt it really was working reliably, you probably just didn’t hit the race condition as frequently. If all the queries are localized within the database service, they are likely returning Promises anyway. Simply make them dependent on something that fires once the database is ready. The end users (components) shouldn’t have to know or care about any of this.

I am getting the same issue. Can anyone please advise me how I should structure my code here?