Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning true or false from a function in angular 6

Tags:

angular

I'd like to call a function from within another function. My code looks like this: this is my parent-function:

} else {
    if(this.checkIfCountyExists(data.convertedAddress[0].county)) {
       console.log('true');
    } else {
       console.log('false');
    }
}

this is my child-function which gets called within parent-function:

checkIfCountyExists(county: String) {
    this.localisationService.checkCounty(county).subscribe(data => {
        if(data.success) {
            return true;
        } else {
            return false;
        }
    })
}

my service holds an interface for the returned data which looks like this:

interface data {
  success: Boolean,
  convertedAddress: any
}

But the function never gets called correctly, because it returns everytime. So how can i create a function which correctly returns true and false?

VisualStudio says

an expression of type void cannot be tested for truthiness

Where's my mistake?

like image 424
Sithys Avatar asked Apr 17 '26 18:04

Sithys


1 Answers

your method is asynchronous thus it does not wait at your if statement and continues to execute. That is why you are always jumping to else condition.

Convert your checkIfCountyExists method to Observable

checkIfCountyExists(county: String) {
    return this.localisationService.checkCounty(county).map(data => {
        if(data.success) {
            return true;
        } else {
            return false;
        }
    })
}

then

this.checkIfCountyExists(data.convertedAddress[0].county).Subscribe(res => {
       if(res) {
           console.log('true');
       } else {
           console.log('false');
       }
});
like image 89
Derviş Kayımbaşıoğlu Avatar answered Apr 19 '26 08:04

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!