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?
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With