Angular 7 数据绑定被延迟
Angular 7 data binding being delayed
我遇到了 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 以查看控制台是否有延迟。
我是不是做错了什么?
如有任何帮助,我们将不胜感激。
如上所述,问题是传递给 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);
}
});
});
}
我遇到了 Angular 的数据绑定被延迟的问题。
当 this.notAvailable
的值更改时,[class.hide]
直到代码 运行.
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);
}
});
});
}