【问题标题】:Angular 7 data binding being delayedAngular 7 数据绑定被延迟
【发布时间】:2018-11-06 16:24:50
【问题描述】:

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

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 以查看控制台是否存在延迟。

我在这里做错了吗?

任何帮助将不胜感激。

【问题讨论】:

  • console.log后面加上changeDetectionRef->detectChanges怎么样?
  • 这听起来像是代码在 Angular 区域之外运行(即this.geocoder.geocode({'address': postcode}, (result, status) =&gt; { ... probably this code ... })。如果您将区域注入到您的组件中(即constructor(private ngZone: NgZone) {})并将代码包装在该回调中,您的问题应该是固定的。
  • @DanielWSrimpel 这可以更快地运行代码,但会不断返回 REQUEST_DENIED。
  • 你有没有试过console.logstatus看看会发生什么?
  • 是的,它正在返回 REQUEST_DENIED,然后在我一直在测试的邮政编码上返回 OK。

标签: javascript angular google-maps data-binding geocoding


【解决方案1】:

如上所述,问题在于传递给 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);
      }
    });
  });
}

【讨论】:

  • 很抱歉让您感到痛苦,但这可以更快地运行代码,但现在不断地从地理编码返回 REQUEST_DENIED。
  • @HenslerSoftware 您是否在浏览器中检查了请求以查看返回的结果和状态是什么?完全按照上述方式在 Angular 的区域中运行代码不应影响 resultstatus 值。
  • 这是工作对不起。由于某种原因,我遇到了 API 问题,我随机得到这个 API 项目无权使用这个 API。我现在已经更新了 API 密钥,并且这个错误显示了每几次 API 调用。那是标准吗?我不会打太多电话。
猜你喜欢
  • 2014-05-24
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多