簡體   English   中英

如何在執行下一行代碼之前使await訂閱塊完整?

[英]How can I make the await subscribe block complete before executing next line of code?

我正在訂閱Google Maps API以根據地址提取坐標。 我的理解是,通過等待訂閱行,它應等待該代碼塊完成,然后再移至以下行。

  async getCoordinates(address) {
      let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&key=' + environment.geocodeKey;
      let lat;
      let lng;
      let coord: Coordinate;
      await this.http.get(url).subscribe(data => {
          let map = data.json() as Results;
          lat = map.results[0].geometry.location.lat;
          lng = map.results[0].geometry.location.lng;
          console.log("inner lat is: " + lat)
      });
      console.log("outer lat is: " + lat)
      coord = new Coordinate(lat, lng);
      console.log("coord lat is: "+ coord.latitude)
      return coord;
  }

但是,當我運行該應用程序時,我會在控制台中看到以下內容:

outer lat is: undefined
coord lat is: undefined
inner lat is: 38.912799

這向我表明,等待塊中的代碼正在最后執行。 我沒有異步/等待也有相同的結果。 我如何才能使訂閱代碼首先執行,並使其他代碼等到lat和lng都具有值? 現在,它們僅在subscribe塊內具有值,但我不能像此答案所示那樣在其中放入返回行。

我已經讀到,Angular中的await / async本質上是與promise和callback相同的東西。 我已經通過使用.then()將這個異步getCoordinates函數的結果視為一個承諾:

service.getCoordinates(this.address).then(
    (val) => this.coordinates = val,
    (err) => console.log(err)
);

Angular的http服務返回一個Observable 您可以使用rxjs toPromise運算符將其轉換為toPromise

import 'rxjs/add/operator/toPromise';

await this.http.get(url).toPromise().then()
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM