【发布时间】:2020-04-25 06:59:11
【问题描述】:
我有一个从 API 返回数据的 Observable。在这种情况下,可以返回 3 种类型的地址,Office、Mailing 和 Home。但是在用户没有提供家庭地址的情况下,API 响应中不存在该元素。
我用
setInitialValue() {
this.userForm.setValue( {
home_address_city = this.userProfile.home_address.city
})
}
只要该元素存在,它就可以正常工作。所以我想知道如果 this.userProfile.home_address.city 不存在,最安全的处理方法是什么
【问题讨论】:
-
为什么不添加空检查?
home_address_city = this.userProfile.home_address.city ? this.userProfile.home_address.city: 'No address'。如果响应中不存在该属性,则将设置undefined,这仍然可以,因为它不是错误。 -
对阿米特的回应稍作修正。 home_address_city = this.userProfile.home_address? this.userProfile.home_address.city: 'No address' 之前的响应仍然假设用户配置文件总是有一个家庭地址。如果没有,你会得到一个错误。
-
@Edward 是的,完美。谢谢! TBH,我没有注意到
city属性。我以为home_address.city是userProfile下的一个单一道具。 -
是的,我刚刚尝试了 Amit 的答案,只要响应中有一个 home_address: {} 它就可以正常工作,但是一旦它丢失,我就会收到错误“无法读取属性。那么如何我正确检查了 home_address 和 city 的 null。我假设检查 this.userProfile.home_address? 只会检查 home_address 是否存在而不是下面的城市元素
-
@NoSoup4You
home_address_city = this.userProfile.home_address ? this.userProfile.home_address.city : '';如果 home_address 被定义,这只会尝试获取“城市”属性。如果您还需要检查“userProfile”是否存在,那么您可以执行home_address_city = (this.userProfile && this.userProfile.home_address) ? this.userProfile.home_address.city : ''
标签: angular