我遇到了 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/