2016-09-25 3 views
2

각도 프로그래밍 및 웹 프로그래밍의 초보자입니다. 그러나 내가 배운 것을 사용하여 Google Maps API를 사용하여 Angular2 구성 요소를 만들고 두 점 사이를 라우팅하지만 API의 응답에 따라 해고되는 일반 함수 대신 Observable을 사용하려고합니다. 어떤 도움을 주시면 감사하겠습니다. 여기 내 코드는 다음과 같습니다.Angular2에서 관찰 가능한 Google지도 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

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