【问题标题】:How to get data from asynchronous call in angular service?如何从角度服务中的异步调用中获取数据?
【发布时间】:2018-08-05 07:58:46
【问题描述】:

我正在尝试从 Google Maps API 的异步方法返回数据。

这就是我的服务的样子。

    export class GMapsService {

  test = 'a';

  // public mysubject: Subject = new Subject();

  getData() {
    var origin1 = 'austin, TX';
    var destinationA = 'Dallas, TX';
    var service = new google.maps.DistanceMatrixService();

    return service.getDistanceMatrix(
      {
        origins: [origin1],
        destinations: [destinationA],
        travelMode: 'DRIVING',
        avoidHighways: false,
        avoidTolls: true,
      },
      function (response, status) {
        return response
        // return data back to component
// mysubject.next(response);
      }
    );
  }
}

我想在数据从地图 API 返回时获取发送到组件的数据。此外,是否可以在数据更改时更新组件(不是在这种情况下)。我尝试使用主题,但我相信我遗漏了一些东西。

this.GMapsService.mysubject.next("My favourite value");

    this.GMapsService.mysubject.subscribe((value) => {
      //insert your code here

      console.log(value);

    });

【问题讨论】:

    标签: angular observable angular-services angular-components angular-observable


    【解决方案1】:

    尝试将回调函数提供为箭头函数,以便回调的上下文将保留 GMapsService 实例。

     return service.getDistanceMatrix({
            origins: [origin1],
            destinations: [destinationA],
            travelMode: 'DRIVING',
            avoidHighways: false,
            avoidTolls: true,
          },
         (response, status) => {
    
            // return data back to component
            this.mysubject.next(response);
         }
     );
    

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多