这里是我的角度组件
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 = this
,self.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);
我使用了一个非常简单的例子来说明可观察量是如何工作的。您可能应该提取对单独服务的方向调用,并在那里使用可观察的方法。