我正在添加用户地理位置,并且想在将数据推送到数组之前检查snapShot.data()。location.geopoint是否为null,但是我仍然收到以下错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'geopoint' of undefined
TypeError: Cannot read property 'geopoint' of undefined
这是实际的代码吗?
query.get()
.then(list => {
list.forEach(snapShot => {
let userLat = (snapShot.data().location.geopoint.latitude > 0) ? snapShot.data().location.geopoint.latitude : 0;
let userLong = (snapShot.data().location.geopoint.longitude > 0) ? snapShot.data().location.geopoint.longitude : 0;
console.log('use lat long', userLat, userLong);
let distance = this.geo.distance(this.geo.point(myLat, myLong), this.geo.point(userLat, userLong));
if (distance <= this.userSettings.distance.upper) {
this.userInfo.push({
userId: snapShot.data().userId,
displayName: snapShot.data().displayName,
});
}
});
})
鉴于它抱怨我添加的实际null检查,我如何在geopoint中检查null值:
let userLat = (snapShot.data().location.geopoint.latitude > 0) ? snapShot.data().location.geopoint.latitude : 0;
答案 0 :(得分:2)
您可以使用snapshot.get(fieldPath)
API(docs)并执行以下操作:
let userLat = 0;
let userLong = 0;
if (snapShot.get("location.geopoint")) {
userLat = snapShot.get("location.geopoint").latitude;
userLong = snapShot.get("location.geopoint").longitude;
}