首页 > 解决方案 > 如何使用来自 Google Maps DirectionsService.route() 函数的 Angular 双向绑定?

问题描述

这是我的 Angular 组件

export class MapsComponent implements OnInit {

  @ViewChild('googleMap') gmapElement: any;
  map: google.maps.Map;  
  data = "initialised";

  ngOnInit() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;

      var map =  new google.maps.Map(this.gmapElement.nativeElement, {
            zoom: 7,
            center: {lat: 41.85, lng: -87.65}
      });
      directionsDisplay.setMap(map);
      directionsService.route({
          origin: "terrell hills, tx",
          destination: "alamo heights, tx",
          travelMode: google.maps.TravelMode.DRIVING
        },  (response, status) => {
          if (String(status) === 'OK') {
            directionsDisplay.setDirections(response);
            this.data = "I'm modified in directionsService";
            /***********************************************
             here some string is assigned to this.data, but it was not updated in the "data" member of this class. The value of the member "data" is always showing "initialised" in the HTML template.
             ***********************************************/
          } else {
            alert('Directions request failed due to ' + status);
      }
    });
  }

这是我的模板

<span>{{data}}</span> <!-------------here the the data is always showing "initialised"-------------->

有人可以告诉我是什么问题。

有人可以帮我吗?提前谢谢了。

标签: javascriptangulartypescriptgoogle-maps

解决方案


未检测到更改,因为它发生在 google 方向回调中的角度框架之外。你有几个选择。我将按照从概念上最简单到最难的顺序列出它们。

力变化检测

constructor(private ref: ChangeDetectorRef){}
....
if (String(status) === 'OK') {
    directionsDisplay.setDirections(response);
    this.data = "I'm modified in directionsService";
    this.ref.detectChanges();
...

在 Angular2 区域中运行

constructor(private ngZone:NgZone) {}
...
this.ngZone.run(() => {
    -- Run directions query here
});
...

将方向调用包装在可观察对象中

const directionsObservable = Observbable.create(observer => {
    directionsService.route({
      origin: "terrell hills, tx",
      destination: "alamo heights, tx",
      travelMode: google.maps.TravelMode.DRIVING
    },  (response, status) => {
      if (String(status) === 'OK') {
        directionsDisplay.setDirections(response);
        observer.next("I'm modified in directionsService");
      } else {
        alert('Directions request failed due to ' + status);
  }
});
directionsObservable.subscribe(text => this.data = text);

我使用了一个非常简单的示例来说明可观察对象的工作方式。您可能应该将方向调用提取到单独的服务,并在那里使用 observable 方法。


推荐阅读