Utilizing Ionic to implement a conditional statement for comparing a string with information retrieved from an Observable source

I have a piece of code where I fetch data about a country as an observable. I then attempt to compare my string this.city with the this.capital that I got from the Observable. If they are not the same, I want to show a new paragraph in the HTML by changing the hidden boolean to false. Even though I am certain that this.city and the observable this.capital are not equal, the paragraph does not display on the HTML after calling showHeader(). I'm curious if it is possible to compare Observable data with strings in this manner?


    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);
      };
     }
    

Answer №1

When using then on

this.storage.get("city")
, it's important to note that this.city may not be set yet when calling this.cdp.getCityData(this.city). Make sure to properly use await.

Here are some basic tips:

  • Instead of
    if(a == b){...} else if(a != b){...}
    , you can simply use if(a == b){...}else{...}
  • Similarly,
    if(condition){value = true}else{value = false}
    can be shortened to value = condition

async 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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Is there a way to dim and deactivate a button after it has been clicked once?

Hello, I am attempting to disable and grey out a button after it has been clicked once in order to prevent the user from clicking it again until they refresh the page. I hope my question is clear enough and that you can understand me. Below is the HTML cod ...

What is the best way to combine two JavaScript functions into a single function, especially when the selector and function to be invoked may differ?

In the provided snippet, I am using the following function callers: // del if ( maxDelivery > 0 ) { if ( maxDelivery === 1 ){ delAdressFunc( dels ); } else { for ( i = 0; i < maxDelivery; i += 1 ){ delAdressFunc( ...

`How can a child component in Next.js send updated data to its parent component?`

Currently diving into Next.js and tinkering with a little project. My setup includes a Canvas component alongside a child component named Preview. Within the Preview component, I'm tweaking data from the parent (Canvas) to yield a fresh outcome. The b ...

When the "open" prop is set to "true", the DRAWER component from @material-ui/core fails to display

Help Needed: I'm struggling to make the drawer component open when the variant prop is set to "temporary". Material-UI Package Used: @material-ui/core I have integrated Material UI's drawer component into my custom Nav component. However, I am ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

nextJS does not recognize the term 'Window'

I'm encountering the error "window is not defined" in my NextJS project. The variable isMobile determines whether the window size is less than 767.98 to handle the hamburger menu functionality. This code worked in ReactJS but seems to be causing issue ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Triggering a click event on an anchor <a> element

Seeking help with a Javascript event query. I have an <a> tag set up like this: <a id='aTag' href='http://example.com'>Click to redirect</a> When attempting to trigger the click event using: <script> $('#a ...

The absence of angular-cli.json is evident, as it is not hidden from

Recently starting an Angular course, I encountered an issue where my angular-cli.json file was missing. Despite researching online and checking hidden files, I still couldn't locate it. Even creating a new project didn't solve the problem. I&apo ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

Is there a way to dynamically shift arrow key focus onto buttons in Angular using the left and right arrow keys?

I am facing an issue where pressing the arrow keys left and right does not focus or allow me to navigate through these buttons using the arrow keys. However, when checking the keycode values, they are printed according to the key pressed. I would like to k ...

Populate a chart in real-time with data pulled directly from the Component

I'm completely new to Angular and I feel like I might be overlooking something important. Within my component, I have 3 variables which are populated after invoking the .subscribe method on an observable object. For example: this.interRetard = this ...

Navigate to a specific moment in an HTML5 audio track by clicking on the progress bar

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var counter = 0; ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

What is the best way to update data in Highcharts with Vue 3?

Issue with Updating Highcharts Data Using Vue.js 3 Within my Vue.js 3 web application, I have integrated a Highcharts Chart alongside some statistics display. This setup includes global buttons for time-filtering options such as All, Year, Month, and Week ...

Troubleshooting the issue with Protractor/Jasmine test when browser.isElementPresent does not detect a class in the

As a newcomer to Jasmine testing, I've been facing some challenges while running my tests. Specifically, I have been struggling with my webdriver closing the browser before it can check the '.detailsColumn' element for expected results. Afte ...

Tips for aligning elements of varying heights

Currently, I am tackling a responsive web design challenge involving floating multiple items in 4 columns side by side. The issue arises due to the varying heights of these items, causing the floating to behave improperly. Here is the current problem illu ...