google-maps - 无法在地理编码函数内分配组件变量值
问题描述
GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng(); <== this.lat value is undefined
}
else {
alert("Something went wrong : " + status);
}
});
}
在这里,我无法在地理编码函数中分配组件级变量“lat”和“lng”的值。仅供参考:它里面的结果的位置对象中有值,但是在分配值之后它仍然是未定义的我不知道为什么?
解决方案
import { Component, OnInit, NgZone } from '@angular/core'; <= 1. I have to import NgZone
constructor(private ngZone: NgZone) { } <= 2. declared it here
ngOnInit() { }
GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => this.ngZone.run(() => { <= 3. and used it here
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
}
else {
alert("Something went wrong : " + status);
}
}));
}
我找到了解决方案。我必须从 '@angular/core' 导入 NgZone 并在回调函数中使用 this.ngZone.run() 函数,如 3. 提示。
推荐阅读
- javascript - Vanilla JS - 无限自动播放滑块
- python - 将脚本导入另一个脚本以编辑变量时出现 ModuleNotFoundError
- flutter - 使用 Riverpod 打开页面时如何进行多个异步调用?
- node.js - Teams Bot 如何收听来电?
- python - 基于日期时间对象添加季节列时遇到问题
- r - R - 确定符合预定义标准的配置文件(四个类别)的所有组合
- swift - UICollectionView 中 MTKView 重叠的单元格
- spring - Spring-boot:将@EnableWebMvc 支持添加到现有的@EnableWS 应用程序?
- reporting-services - 自定义表达式值的 SQL Server Report Builder submation
- r - 合并来自大约的数据。R中的70个表