Search code examples
javascriptangulartypescriptangular-httpclient

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

Solution

  • 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 => {
      ...
    });