hY8vVpf3tyR57Xib
hY8vVpf3tyR57Xib

Reputation: 3915

Understanding how to deal with observable returns from http calls

I just started with an Angular 2 app that makes some http calls and this introduced me with Observables. I am still having a hard time in learning how to deal with them, the documentation is a bit lacking for beginners. I'll give a short example to illustrate the difficulties that I encounter:

getValue() {        
        let headers = new Headers({ 'Content-Type': 'text/plain' });
        let options = new RequestOptions({ headers: headers });
        return this.http.get('http://url/boolean.json', options)
}

This is a get call that returns a boolean value. Now if I would want to use this value in a function I instinctively would expect that I could assign a variable like this:

let varName = this.getValue()

Obviously this isn't possible, I read that in order to get output from an observable you need to subscribe to it. Isn't there a possibility to let my function getValue() return a boolean and not an observable? In this case however, since I only need to have boolean value, I am not sure if asynchrounous programming makes sense? It's not as if this can take a long time. Is there also a way in Angular 2 to get rid of this asynchronous behavior (for simple functions like this?)?

Upvotes: 1

Views: 512

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202346

You can "simulate" a pseudo synchronous mode using the async pipe of Angular2:

<div>{{value | async}}</div>

In this case value is the observable and not the content of the HTTP response.

This way Angular2 subscribes for you under the hood and manage the corresponding subscription. When the data is received, template is updated accordingly.

You can't actually bypass the asynchronous mode since it's the way underlying API (XMLHttpRequest) works to execute HTTP requests (and more generally JavaScript).

You can notice that Rx / Observables are really powerful to chain processing. For example, you can leverage operators like flatMap and you can only subscribe at the end of the chain. Here is a sample:

this.getValue().flatMap((data) => {
  // return another observable
  return this.getAnotherRequest();
}).subscribe((data) => {
  // data is the result of the second request
});

This Rx tutorial could help you:

Edit

Here is the way to leverage operators:

this.getCurrentUser().flatMap((user) => {
  // return another observable
  return this.getData(user);
}).subscribe((data) => {
  // data is the result of the second request
}, (err) => {
  // no current user, ...
});

Upvotes: 2

Related Questions