I have an Angular 5 application in which I have to call some heavy REST service (usually takes some seconds). I need its result in different part of application, so I would like to store the result in a DataStorageService. Basically, this is I would like to achieve:
@Injectable()
export class DataStorageService {
private result: MyCustomObject;
constructor(private service: Service) {}
getResult(): MyCustomObject {
if (typeof this.result === 'undefined') {
// save result
}
return result;
}
The question is how I can wait until HTTP request is finished and then save and return the 'result' object. I tried to solve it using Promise and Observable as well, but none of them worked fine.
Observable:
if (typeof this.result === 'undefined') {
this.service.call()
.subscribe(response => this.result = response);
}
return this.result; // wait for save and return MyCustomObject
Promise:
if (typeof this.result === 'undefined') {
this.service.call()
.toPromise()
.then(response => this.result = response);
}
return this.result; // wait for save and return MyCustomObject
Let you have getData() function to call an api , which fetch data asynchronous , but to make synchronous api call, let's wrap this function inside a another function to make a call that return to promise and use async/await in component.
1.1 The Angular HTTP Client It is a wrapper over the JavaScript XMLHttpRequest API. The API is asynchronous. JavaScript is single-threaded. Doing a blocking synchronous HTTP call will otherwise freeze the UI.
Angular is a great framework but writing asynchronous code and making asynchronous calls is hard. Especially if you can't decide between Async/Await and Angular Promise.
The differences between asynchronous and synchronous include: Async is multi-thread, which means operations or programs can run in parallel. Sync is single-thread, so only one operation or program will run at a time.
Try using await/async
async getResult(): Promise<MyCustomObject> {
if (typeof this.result === 'undefined')
{
// save result
this.result = await this.service.call()
.toPromise()
.then(resp =>resp as MyCustomObject);//Do you own cast here
}
return this.result;
}
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