javascript - 无法在回调内设置 Angular 变量

标签 javascript angular google-maps typescript directions

我正在使用 Google map 路线服务来计算行程时间。

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


});

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

最佳答案

使用 NgZone 确保回调将绑定(bind)到范围。工作示例:

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

关于javascript - 无法在回调内设置 Angular 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290087/

相关文章:

javascript - Angular 6 typescript 与 KotlinJs 的集成

javascript - d3.js map 上的跳动标记点

javascript - AngularJS - 如果 ng-option 为空,则隐藏 <select> 元素

javascript - HTML5 跨域 XmlHttpRequest 与旧的 XmlHttpRequests

java - 如何使用带有 Quarkus 的 Vertx 路由器将所有未找到的路由重定向到 index.html?

c# - User.Identity.Name 在 asp.net core + Angular 客户端应用程序中为 null

javascript - 缺少KeyMap错误: Error while using Google Maps Autocomplete text box on local host

javascript - map.getBounds() 奇怪的行为(未捕获的类型错误 : Cannot read property 'getNorthEast' of undefined)

javascript - 为什么每个 javascript 对象都有构造函数属性?

javascript - 值小于长度的数组 - json 中的 null 开销