Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for response from HttpClient get - synchronous call

I am wondering how to wait for the response from an HttpClient action that is calling a backend, my need is to wait until the backend returns gives response (synchronous call), the classic approach is to subscribe to the Observable response :

//My component
...
console.log("before");
this.myService.getSomeThingFromBackend('param_value').subscribe(response => {
     console.log("do my stuff");
}
console.log("after");

//My Service
...
getSomeThingFromBackend(param: string): Observable<any>{
        return this.httpClient.get(this.host + this.url+ "/" + param);
}

this shows :

before

after

do my stuff

And I want this result :

before

do my stuff

after
like image 429
medmoufahim Avatar asked Sep 04 '26 22:09

medmoufahim


1 Answers

Angular's this.http.get returns an RxJS Observable. Then calling this.http.get(...).subscribe(...) returns RxJS Subscription object. So none of them return Promise so you can't use them with await.

If you want to be able to use await with Observables you have to use toPromise() instead of subscribe() that returns a Promise that is resolved with the first value emitted by that Observable (it internally calles subscribe for you and wraps it with a Promise object).

await this.http.get(...).toPromise(value => {
  ...
});
like image 93
Sanjay Lohar Avatar answered Sep 07 '26 13:09

Sanjay Lohar



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!