【问题标题】:Show nothing if null (JS)如果为 null (JS),则不显示任何内容
【发布时间】:2019-04-17 07:21:24
【问题描述】:

我有组件,我在其中显示数据,从后端获取。

这是显示数据的功能

 getData() {
    this.propertyService.getPropertyForEdit(Number(this.activatedRoute.snapshot.params['id'])).subscribe(r => {
        this.property = r;
        this.tabTemplates = [
            { title: this.l('Addresses'), template: this.addressesTemplateRef },
            { title: this.l('Site'), template: this.siteTemplateRef}
        ];
        this.propertiesToDisplay = [
            { displayName: this.l('PropertyTitle'), value: this.property.propertyTitle.name},
            { displayName: this.l('Landlord'), value: this.property.landlord.name},
            { displayName: this.l('Agent'), value: this.property.agent.name },
            { displayName: this.l('BuildingType'), value: this.property.buildingType.name }
        ];
    });
}

在这一行中value: this.property.landlord.name} 的值可以为空。

所以当它为空时,我有错误

无法读取未定义的属性“名称”

我该如何解决这个问题?

【问题讨论】:

  • this.property.landlord.name || "N/A" 试试这个
  • this.property.landlord 未定义。您应该使用 fallbacks 检查是否存在房东。 (this.property && this.property.landlord && this.property.landlord.name) ? this.property.landlord.name : 'N/A'
  • 或使用 .map 并对所有未定义的值执行相同操作。

标签: javascript typescript object


【解决方案1】:

所以当它为空时,我有错误

无法读取未定义的属性“名称”

不,不是null,是undefined,不一样。

抛出错误是因为this.property.landlordundefined。在 javascript 中,尝试访问 undefined 的属性(在本例中为 name)会引发 TypeError,这是设计使然。

要解决问题(这不是问题,而是案例),您应该使用 fallbacks 来检查属性的祖先是否存在。在这种情况下,我会这样处理:

{ displayName: this.l('Landlord'), value: (this.property && this.property.landlord && this.property.landlord.name) ? this.property.landlord.name : 'N/A'},

具体那段代码:

this.property && this.property.landlord && this.property.landlord.name

将断言name 的每个祖先都存在。如果其中任何一个没有,它将返回 'N/A' 而不会引发任何异常。

【讨论】:

  • @EugeneSukh 从您的帖子中,我可能猜到您使用的是angular。如果是这样的话,如果变量直接打印在html模板中,可以使用elvis操作符来避免上面的检查,但是只能在angular模板中使用:@ 987654332@。如果是这样,你可以看看这个:stackoverflow.com/questions/35161789/…
【解决方案2】:

使用三元运算符:

value: (this.property.landlord ? this.property.landlord.name : "defaultValue")

【讨论】:

    【解决方案3】:

    问题是楼主是null(undefined)。 您可以使用三元运算符直接处理null 检查。

    value: (this.property.landlord) ? this.property.landlord.name : null

    【讨论】:

      【解决方案4】:

      赋值时使用三元条件。像这样

      { displayName: this.l('PropertyTitle'), value: (this.property.propertyTitle.name) ? this.property.propertyTitle.name: null},
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多