处理Angular中的异步操作

时间:2018-04-07 16:53:07

标签: angular asynchronous

在我的服务中,我正在使用来自HttpModule的Http服务。我正在使用http.get()方法从API获取JSON响应。 http.get()方法返回一个Observable。我在我的Component中订阅了这个Observable。

在同一服务中,还有另一个http.get()方法从另一个API获取数据。同样,我在我的组件中订阅了这个Observable。

我想使用这两种方法提供的值,执行一些计算,然后将答案呈现给我的HTML页面。但是,由于操作是异步的,我无法在组件中执行计算,因为它给了我一个未定义的答案。所以,我必须在我的HMTL页面上执行计算。我不想这样做,因为我在不同的组件中使用相同的服务,我多次重复我的代码。

有更好的方法吗?

这是我在服务中使用的方法

getAnswer() {
    return this.http.get(this.url1)
    .map(res => res.json());
}

getAnotherAnswer() {
    return this.http.get(this.url2)
    .map(res => res.json());
}

这是我的组件

Service.getAnswer().subscribe(res=>{
  this.ans1= res;
});

Service.getAnotherAnswer().subscribe(res=>{
  this.ans2= res;
});

假设我从API中获得了两个数字,并且我想添加这两个数字,我必须在我的HTML中这样做

<h3> {{ ans1 + ans2 }}</h3>

我想在我的Component中进行此计算,但我不能,因为这些值是异步的,当我尝试添加它们时,我得到一个未定义的答案。

如何在我的组件中添加这些值?

1 个答案:

答案 0 :(得分:0)

您可以使用可观察的运算符

Observable.zip(Service.getAnswer(), Service.getAnotherAnswer()).first().subscribe(res =>{
  [this.ans1, this.ans2] = res;
  // or you can do calculation here and write it to a single variable
  // to show it in template
});
顺便说一句,如果你有rxjs 5.5+,你可以用更好的方式编写它,以便在包内保持较小的rxjs

相关问题