Hi all,
we are currently creating our first ionic 2 app. Inside the app we are saving data using the Storage module which is wrapped in an own storage provider.
Now, we want the app to wait / show the splashscreen until the storage provider signalizes that all data has been read from the storage. Therefore, we implemented a function called “readData” inside the storage provider which returns an Observable and signalizes readiness as soon as all keys have been read from the Storage.
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class StorageProvider {
private entries: { [key: string]: any} = {};
constructor(public storage: Storage)
{
}
public readData(): Observable<boolean>
{
return Observable.create(observer => {
console.log('Reading from storage...');
this.storage.forEach((value, key, index) => {
this.entries[key] = value;
console.log('Read key '+key+' with value '+value+' from storage.');
});
observer.next(true);
observer.complete();
});
}
}
Inside the initializeApp method of app.components.ts (first method called in constructor) we now subscribe to the result of the readData method and afterwards hide the splashscreen:
import { Component, ViewChild } from '@angular/core';
import { Platform, MenuController, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { StorageProvider } from '../providers/storage/StorageProvider';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
// make HelloIonicPage the root (or first) page
rootPage: any = NewsPage;
constructor(
public platform: Platform,
public storage: StorageProvider
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.storage.readData().subscribe(ready =>
{
Splashscreen.hide();
StatusBar.styleDefault();
})
});
}
}
Well, it does not work. The splashscreen disappears but the data seems not to be loaded.
Did we understand wrong how observables work? Is there another / better way to achiece our goal?
Thanks,
Thomas