I am developing a web application using Angular 8. I have a problem using JavaScript with an asynchronous function. I have created a service that has a public method: this method examines a condition that can vary over time and in one case (true) it updates its data with a response to an HTTP call; in the other case (false) it returns the data it already has. Here is a code example:
private date; // My date
getMyDate() {
if(my_boolean_condition) {
this.http.post(this.myUrl, JSON.stringify(this.myInputData)).toPromise().then((data: any) => {
this.date = data;
return this.date;
}
} else {
return this.date;
}
}
I know perfectly that something is wrong with this code, but I don't understand what.
If a client (for example an Angular component) calls my getMyDate()
method, the return value is however undefined
.
What I want is for the method to always return a value different than undefined
, whether it makes the HTTP call or doesn't.