Как использовать угловое двустороннее связывание из функции Google Maps directionsService.route ()? - PullRequest
0 голосов
/ 29 августа 2018

Здесь мой угловой компонент

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"-------------->

Может кто-нибудь подскажите, пожалуйста, в чем проблема.

  • Значение alert(this.data) перед строкой this.data = "I'm modified in directionsService"; инициализировано
  • Значение alert(this.data) после строки this.data = "I'm modified in directionsService"; равно Я изменен в directionsService
  • Но основной член класса data не обновляется.
  • Я также пытался создать другую функцию function testFunc(x:any) { this.data = x; } Теперь вызов этой функции this.testFunc("some text") из ngOnInit() успешно обновляет data Но вызов функции this.testFunc("some text inside directionsService.route") из directionsService.route не обновляет значение data
  • Я также пробовал var self = this вне функции, и self.data = "some text with self" также не работает.

Может кто-нибудь помочь мне с этим? Спасибо заранее.

1 Ответ

0 голосов
/ 29 августа 2018

Изменение не обнаружено, поскольку оно происходит за пределами угловой структуры в обратном вызове направления 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);

Я использовал очень простой пример того, как будет работать наблюдаемая. Вам, вероятно, следует извлечь вызов направлений для отдельной службы и использовать там наблюдаемый метод.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...