Summary of Issue : Angular method does not wait till response is received from REST call before RETURNING the value
Description of Problem:
- I have an endpoint that once consumed returns a date from the database. What I intent to do is write a common method in Angular (I have created a method inside a provider service) that every time called by any component will do this REST call and return the date from the response.
- Below is the method that does GET REST call
getDateFromDb() {
return this.httpClient.get(this.host + "/api/get-date");
}
- Below is the method inside provider service that calls getDateFromDb() method and should return date from the response
async fetchDate() {
await this.rest_service.getDateFromDb().subscribe((response: any) => {
if(response)
return response.date;
}, error => {
this._alert.alertError('Error occurred');
});
}
I tried async/await, promises, observables but could not find workable solutions. Let me know if anything is wrong with the implementation.
I also cannot use local variables as well as this fetchDate() method is inside provider service and not in component. So cannot use something like this.
async fetchDate() {
await this.rest_service.getDateFromDb().subscribe((response: any) => {
if(response)
this.date = response.date; //Cant' do
}, error => {
this._alert.alertError('Error occurred');
});
}
- I want to be able to call fetchDate() method in any component and assign the value. Eg
this.date = this._provider_service.fetchDate(); //Inside component A
or
let obj = { //Inside component B
foo: //some default value
date: this._provider_service.fetchDate();
}