如果null(JS)则不显示任何内容

问题描述 投票:0回答:4

我有组件,我显示数据,从后端获得。

这是显示数据的功能

 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}值可以为null。

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

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

我怎么解决这个问题?

javascript typescript object
4个回答
3
投票

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

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

不,它不是null,它是undefined,这是不同的。

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

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

{ 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'而不抛出任何异常。


2
投票

使用三元运算符:

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

2
投票

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

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


1
投票

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

{ displayName: this.l('PropertyTitle'), value: (this.property.propertyTitle.name) ? this.property.propertyTitle.name: null},
© www.soinside.com 2019 - 2024. All rights reserved.