0

I have a function as below where I need to make a call to the server and get a value that the function returns. I am using rxjs subscribe. I get the value but since rxjs is async the function returns before the value is obtained from the server. Below is a pseudo code to explain what I am trying to do:

..

let myValue = getValue();
private getValue(): string {
 let val = '';
    this.httpClient.get('/server url', { observe: "response" }).subscribe(res => {
                val = res.headers.get('X-Some-Header-Name');
            });}
    return val;
}
..

I know that susbscribe returns right away and hence the function getValue does not return the value from the server. Is there a way I can make the function return teh value only when observable returns?

F. K.
  • 694
  • 3
  • 9
  • 23
  • 1
    No, see https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside – martin Apr 05 '20 at 20:06
  • 1
    You cannot return synchronous data from an asynchronous request. You could either assign the value to the variable inside the subscription or if you need use the variable in the template, use the observable directly in the template with the `async` pipe. – ruth Apr 05 '20 at 23:07

2 Answers2

2

As @satanTime already pointed out in his answer, you should work with the Observable that the HttpClient returns.

You can then also work with myValue in your template using the async pipe, for example:

<p>{{myValue | async}}</p>

Reference: https://angular.io/guide/observables-in-angular

1

if you need to wait for the response then you need to return an observable and to subscribe to it in place where you need the value.

let myValue = getValue();
private getValue(): Observable<string> {
    return this.httpClient.get('/server url', { observe: "response" }).pipe(
        map(res => res.headers.get('X-Some-Header-Name')),
    );
}
satanTime
  • 12,631
  • 1
  • 25
  • 73