我有一个问题,角的数据绑定被推迟。
当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,以查看控制台中是否有延迟。
我在这里做错什么了吗?
任何帮助都将不胜感激。
发布于 2018-11-06 16:45:18
如上所述,问题是传递给this.geocoder.geocode(...)方法的回调代码是在角区域之外执行的。当发生这种情况时,角不知道对this.notAvailable属性的更改,直到有其他东西触发角来执行沿途的更改检测周期。要解决这个问题,您将需要获得对角区域的引用,并包装进行更改的代码,以便ar角知道执行更改检测周期。
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);
}
});
});
}https://stackoverflow.com/questions/53175943
复制相似问题