In this code I retrieve data about a country as an observable. I then try to compare my string this.city with this.capital which I retrieved from the Observable. If the two do not equal I want to display a new paragraph in the html by changing the hidden boolean to false. I know that this.city and the observable this.capital are not equal but it does not display the paragraph in the html after calling showHeader(). I wonder if you can compare Observable data with strings in this way?
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SettingsPage } from '../../pages/settings/settings';
import { Storage } from '@ionic/storage';
import { CityDataProvider } from '../../providers/city-data/city-data';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
hidden: boolean = true;
hiddenTwo: boolean = true;
city: string;
cityData: any[];
capital: string;
cityLowerCase: string;
constructor(public navCtrl: NavController, private storage: Storage, private cdp: CityDataProvider) {
}
async ionViewWillEnter() {
const data = await this.storage.get("city")
.then((value) => {
if (value == null) { this.hidden = false; } else if (value !== null) { this.hidden = true; }
this.city = value;
})
.catch((error) => {
alert("Error accessing storage.")
})
this.cdp.getCityData(this.city).subscribe(data => {
this.cityData = data;
this.capital = data[0].capital.toString().toLowerCase();
this.cityLowerCase = this.city.toLowerCase();
this.showHeader(this.cityLowerCase, this.capital);
});
}
showHeader(a: string, b: string) {
if (a != b){
this.hiddenTwo = false;
}
}
openSettingsPage() {
this.navCtrl.push(SettingsPage);
};`enter code here`
}
As you are using then on this.storage.get("city"), this.city has not been set yet when you call this.cdp.getCityData(this.city). Just use await properly.
Also, some basic tips:
if(a == b){...} else if(a != b){...} is essentially just if(a == b){...}else{...}if(condition){value = true}else{value = false} is essentially just value = conditionasync ionViewWillEnter() {
try
{
this.city = await this.storage.get("city");
this.hidden = this.city == null;
}
catch (error)
{
alert("Error accessing storage.")
}
this.cdp.getCityData(this.city).subscribe(data =>
{
this.cityData = data;
this.capital = data[0].capital.toString().toLowerCase();
this.cityLowerCase = this.city.toLowerCase();
this.showHeader(this.cityLowerCase, this.capital);
});
}
showHeader(a: string, b: string) {
this.hiddenTwo = a != b;
}