如何使用 Google Maps directionsService.route() 函数中的 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"-------------->

有人可以告诉我问题出在哪里。

  • 初始化this.data = "I'm modified in directionsService";之前的alert(this.data)
  • this.data = "I'm modified in directionsService";alert(this.data)的值是我在方向上被修改服务时
  • 但是主类成员data没有更新。
  • 我还尝试创建另一个函数function testFunc(x:any) { this.data = x; }现在从ngOnInit()调用此函数this.testFunc("some text")已成功更新data但是从directionsService.route调用函数this.testFunc("some text inside directionsService.route")不会更新data的值
  • 我也尝试过在函数之外var self = thisself.data = "some text with self"也不起作用。

有人可以帮我吗?提前非常感谢。

未检测到更改,因为它发生在谷歌方向回调的角度框架之外。您有几个选择。我将从概念上最容易到最难列出它们。

力变化检测

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

在角度2区运行

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);

我使用了一个非常简单的例子来说明可观察量是如何工作的。您可能应该提取对单独服务的方向调用,并在那里使用可观察的方法。

相关内容

  • 没有找到相关文章

最新更新