Ionic 2 RC0: SQLite errors due to loading timing


#1

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:


#2

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: https://www.thepolyglotdeveloper.com/2016/06/working-shared-providers-ionic-2-mobile-app/ that I used and it helped me make it work.

I hope that will help you,
Bogdan


#3

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


#4

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.


#5

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:


#6

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.


#7

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