angular - Ionic2/Angular2 wait for SQLite database to open before querying -
i'm using ionic 2 (angular 2) hybrid app. inject shared provider page display data sqlite3 database , proceed load data. however, on creation of database provider opening database takes time (very little). code (as of moment) not wait database opened before querying, results in error.
how can structure code wait database opened in order evade crash?
the constructor of database provider:
constructor(private platform: platform) { this.platform.ready().then(() => { if(this.isopen !== true) { this.storage = new sqlite(); this.storage.opendatabase({name: "data.db", location: "default"}).then(() => { this.isopen = true; this.storage.executesql("create table if not exists people (id integer primary key autoincrement, firstname text, lastname text)", []); }); } }); console.log('hello database provider');
this provider gets injected constructor of page.
when page (home page) loaded triggers event calls load()
function.
ionviewdidload() { this.load(); console.log('hello home page');
the load function:
public load() { this.database.getpeople().then((result) => { this.itemlist = <array<object>> result; }, (error) => { console.log("load error: ", error); });
i'm hoping can point me in right direction :)
i've found solution problem.
for starters i've added function provider checks if database loaded, if isn't proceeds load it:
public opensqlitedatabase() { return new promise((resolve, reject) => { if(this.isopen) { console.log("db open"); resolve(this.isopen); } else { console.log("db not open"); this.platform.ready().then(() => { this.storage.opendatabase({name: "data.db", location: "default"}).then(() => { this.appsettings.opensqlitedatabase().then(() => { this.appsettings.getsettings().then((result) => { let settings: settings = <settings> result; this.selecteddataset = settings.selecteddataset; this.isopen = true; resolve(this.isopen); }); }); }, (error) => { reject(error); }); }); } });}
as function returns promise (js promises) allows me wait database opened before doing else (such querying).
my function in page-specific typescript file:
ionviewdidload() { this.database.opensqlitedatabase().then(() => { this.loaddictionary(); });}
with code never have problems queries being performed before database has been opened!
Comments
Post a Comment