0

我正在尝试从 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);

    });
4

1 回答 1

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);
     }
 );
于 2018-02-25T22:25:09.753 回答