【发布时间】:2018-11-16 19:38:27
【问题描述】:
我在我的 Angular 5 项目中使用 ngx-toastr。我有用户表单,通过它我将 LAT 和 LNG 用于用户反向地理编码。这是我的代码中应用的条件。
如果未找到城市,则它应该显示toastr 消息,但是当我按下提交按钮时,第一次单击时不会显示此toastr 消息,但当我第二次单击时它会出现。这种行为的原因可能是什么?
这是我的代码:
saveProfile() {
this.getGeoLocation(this.latitude, this.longitude, (val) => {
console.log(val)
l
if (!val) {
console.log('val is null')
this.toastr.error('Latitude , Logitude is not valid', 'Error')
return;
}
...
})
}
这是我的地理编码功能:
getGeoLocation(lat: number, lng: number, cb) {
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(lat, lng);
let request = {
latLng: latlng
};
geocoder.geocode(request, (results, status) => {
console.log(results)
if (results.length == 0) {
cb(null)
}
if (status == google.maps.GeocoderStatus.OK) {
let result = results[0];
console.log(result)
let rsltAdrComponent = result.address_components;
for (let ac = 0; ac < rsltAdrComponent.length; ac++) {
let component = rsltAdrComponent[ac];
switch (component.types[0]) {
case 'locality':
this.cityName = component.long_name;
break;
}
};
if (result != null) {
cb(this.cityName);
} else {
cb(null);
}
}
});
}
【问题讨论】:
-
您确定您没有从 Google API 获得例如空字符串吗?
"" == null在 JS 中是false。顺便提一句。您没有使用严格的相等运算符 (===),这可能会在比较过程中导致意外结果。 -
我认为它的异步问题@magos
-
好的,但是只有烤面包机没有出现或者整个方法没有被调用?您能否告诉我们您如何在模板中调用
saveProfile()? -
我通过 UI 提交按钮以反应形式 @magos 调用它
-
第二次点击时调用toastr
标签: angular google-maps npm angular5 google-geocoder