Currently, I am developing an Ionic application and encountered the following method that invokes an observable:
fetchCountryById(id: number): Promise<Country> {
return new Promise((resolve, reject) => {
this.obtainCountries().subscribe(countries => {
for (let country of countries) {
if (country.Id == id) {
resolve(country);
}
}
resolve(undefined);
}, err => reject(err));
})
}
Here is another method in use:
obtainCountries(): Observable<Country[]> {
if (this.countries) {
return Observable.of(this.countries);
} else if (this.countriesObservable) {
return this.countriesObservable;
} else {
this.storage.get(AppSettings.STORAGE_KEYS.LANGUAGE_APP).then(
language=>{
this.countriesObservable = this.http.get(AppSettings.API_URL + 'api/Countries?locale=' + language).map(json => {
delete this.countriesObservable; // once cached countries are available, we don't need the `countriesObservable` reference anymore
this.countries = json as Country[];
this.countries = this.countries.sort(function (a, b) { return (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0); });
return this.countries;
}).share();
}
).catch(err=>{
});
return this.countriesObservable;
}
}
I suspect that I am retrieving incorrect data. Can anyone guide me on how to modify the second method to ensure it returns a valid Observable so that the first method can function properly? I am still getting acquainted with Promises and Observables. Appreciate your assistance.