gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:34:07 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com