Angular 2等待函数在启动另一个函数之前返回一个值

时间:2017-06-27 11:00:26

标签: javascript function angular service loopbackjs

我对Angular 2很新。

我有2个服务,这个例子可以说位置和价格。 我的第一个服务要求用户位置和返回,货币代码和符号,基于他们的IP地址(不完美,但对于这个例子,没关系)返回以下内容: -

{"code": "EUR","symbol": "€"}

当我尝试从另一个服务中注入一个值时,该服务不会返回任何数据

private Prices(){
  console.log(this.allPrices);
  return this.allPrices;
}

this.locationService.getLocation().subscribe(
  location => {this.currency = location},
    error => console.log("Error: ", error),
    () => {
        console.log(this.currency),
        this.priceApi.find({where: {currency: this.currency.code}}).map(this.Prices)
      }
)

我接近这完全错了吗?

即使你指出了正确的方向,我也会非常感谢你的帮助,所以我能够为自己学习。

如果您要求我发布任何进一步的代码,请告诉我。

提前谢谢!

@str感谢您的反馈

我尝试过我在Chaining Observables in RxJS看到的内容 但它只是console.logs out: -

Observable {_isScalar: false, _subscribe: function}

1 个答案:

答案 0 :(得分:1)

我希望我的问题是正确的。这就是我通过链接2个电话来接近它的方式:

this.locationService.getLocation()
  .flatMap(location => {
    this.currency = location;
    return this.priceApi.find({where: {currency: this.currency.code}})
  }).map(prices => ....)
  .subscribe(...)