无法在回调中设置角度变量

Rub*_*ben 1 javascript google-maps directions typescript angular

我正在使用谷歌地图路线服务来计算旅行时间。

this.mapsAPILoader.load().then(() => {
  const p1 = new google.maps.LatLng(50.926217, 5.342043);
  const p2 = new google.maps.LatLng(50.940525, 5.353626);

  const directionsService = new google.maps.DirectionsService();
  const request = {
    origin: p1,
    destination: p2,
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
  };

  directionsService.route(request, (response, status) => {

    if (status === google.maps.DirectionsStatus.OK) {
      const point = response.routes[0].legs[0];
      // console.log(point.duration.text);
      this.travelTimeDriving = point.duration.text;
    }
  });


});
Run Code Online (Sandbox Code Playgroud)

控制台记录正确的驾驶时间,但我的变量 this.travelTimeDriving 保持为空。
我猜它与回调函数和作用域有关,但我无法修复它。
路由函数也返回无效,没有承诺所以我不能使用 .then()

Jai*_*ule 6

使用 NgZone 确保回调将绑定到作用域。工作样本:

import { Component, OnInit, NgZone } from '@angular/core';
declare const google: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  travelTimeDriving = '';

  constructor(private ngZone: NgZone) {}

  ngOnInit() {
    let mapProp = {
        center: new google.maps.LatLng(51.508742, -0.120850),
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    let map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    const p1 = new google.maps.LatLng(50.926217, 5.342043);
    const p2 = new google.maps.LatLng(50.940525, 5.353626);

    const directionsService = new google.maps.DirectionsService();
    const request = {
      origin: p1,
      destination: p2,
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
    };

    directionsService.route(request, (response, status) => this.ngZone.run(() => {

      if (status === google.maps.DirectionsStatus.OK) {
        const point = response.routes[0].legs[0];
        this.travelTimeDriving = point.duration.text;
      }
    }));
  }
}
Run Code Online (Sandbox Code Playgroud)