1

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?)?

4

1 回答 1

2

async您可以使用Angular2的管道“模拟”伪同步模式:

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

在这种情况下value,是可观察的,而不是 HTTP 响应的内容。

这样 Angular2 在后台为您订阅并管理相应的订阅。当接收到数据时,模板会相应地更新。

您实际上无法绕过异步模式,因为它是底层 API (XMLHttpRequest) 执行 HTTP 请求(以及更普遍的 JavaScript)的方式。

你可以注意到 Rx / Observables 对链式处理非常强大。例如,您可以利用类似的运营商,flatMap并且您只能在链的末端订阅。这是一个示例:

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

这个 Rx 教程可以帮助你:

编辑

以下是利用运营商的方法:

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, ...
});
于 2016-05-10T13:24:23.007 回答