Angular和Web编程中的新手。然而,使用我学到的东西,我使用谷歌地图API创建了一个Angular2组件,它在两点之间进行路由,但我想使用Observable而不是普通函数,它会在API响应时触发。任何帮助将受到高度赞赏。这是我的代码:
import { Component, OnInit, OnChanges } from '@angular/core';
declare var google: any;
@Component({
selector: 'gmap',
templateUrl: 'gmap.component.html',
styleUrls: ['gmap.component.css']
})
export class GMapComponent implements OnInit, OnChanges {
directionsService = new google.maps.DirectionsService();
directionsDisplay;
map;
ngOnInit() {
this.directionsDisplay = new google.maps.DirectionsRenderer();
this.map = new google.maps.Map(document.getElementById('gmap'), {
zoom: 8,
center: { lat: 51.59, lng: -0.44 }
});
this.directionsDisplay.setMap(this.map);
}
onSearchBarGO($event) {
var directionsDisplay = this.directionsDisplay;
//console.log($event);
this.directionsService.route({
origin: $event.from,
destination: $event.to,
waypoints: [],
optimizeWaypoints: true,
travelMode: $event.mode.toUpperCase()
}, function (response, status) {
var parent = this;
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
答案 0 :(得分:1)
您必须使用Observable的转换工厂方法。
Observable.bindCallback(this.directionsService.route)({
origin: $event.from,
destination: $event.to,
waypoints: [],
optimizeWaypoints: true,
travelMode: $event.mode.toUpperCase()
})
.subscribe( function (response, status) {
var parent = this;
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});