javascript - Angular 7 数据绑定(bind)被延迟

标签 javascript angular google-maps data-binding geocoding

我遇到了 Angular 数据绑定(bind)延迟的问题。

this.notAvailable 的值发生更改时,[class.hide] 直到代码运行后大约 5 秒才会在前端更新。

console.log 结果立即显示正确的值,这确实让我困惑为什么会发生这种情况。

代码如下:

xxx.ts

getPostcodeGeo(postcode) {
  postcode = postcode.replace(' ', '');
  this.geocoder.geocode({'address': postcode}, (result, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
      this.notAvailable = false;
      console.log(this.notAvailable);
    }
    if (status === google.maps.GeocoderStatus.REQUEST_DENIED) {
      this.notAvailable = true;
      console.log(this.notAvailable);
    }
  });
}

xxx.html

<div [class.hide]="notAvailable">
  <span>Unable to find address</span>
</div>

起初我认为这是与地理编码器花费一些时间有关,但后来我添加了 console.logs 以查看控制台中是否有延迟。

我在这里做错了什么吗?

任何帮助将不胜感激。

最佳答案

如上所述,问题在于传递给 this.geocoder.geocode(...) 方法的回调代码是在 Angular 区域之外执行的。发生这种情况时,Angular 不会意识到 this.notAvailable 属性的更改,直到其他事件触发 Angular 进行更改检测周期。要解决此问题,您需要获取对 Angular 区域的引用并包装进行更改的代码,以便 Angular 知道执行更改检测周期。

constructor(private ngZone: NgZone) {}

...

getPostcodeGeo(postcode) {
  postcode = postcode.replace(' ', '');
  this.geocoder.geocode({'address': postcode}, (result, status) => {
    this.ngZone.run(() => {
      if (status === google.maps.GeocoderStatus.OK) {
        this.notAvailable = false;
        console.log(this.notAvailable);
      }
      if (status === google.maps.GeocoderStatus.REQUEST_DENIED) {
        this.notAvailable = true;
        console.log(this.notAvailable);
      }
    });
  });
}

关于javascript - Angular 7 数据绑定(bind)被延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53175943/

相关文章:

javascript - 如何在 JQuery 中重新排列数组

javascript - 如何循环遍历数组并使用JS选择没有索引值的元素

angular - ng-bootstrap DatePicker 在触发器 Angular 4 上设置 startDate 和 minDate

javascript - 谷歌地图 api 方向服务在显示多个标记 javascript 之间的路线时提供 OVER_QUERY_LIMIT

javascript - Google Maps API 3 - 根据缩放级别显示/隐藏标记

google-maps - 谷歌地图缩放级别

javascript - 正则表达式:匹配无值

json - 将 header 添加到 API Http 请求、Angular 2、Ionic 2

angular - 我不知道为什么我会在 Angular : "ERROR TypeError: Cannot set property ' position' of undefined"中收到此消息

javascript - 如何访问匿名函数变量?