【问题标题】:Concatenate with Null Undefined not Working in Angular Typescript与 Null Undefined 连接在 Angular Typescript 中不起作用
【发布时间】:2019-12-03 06:35:25
【问题描述】:

我正在尝试连接单词,同时删除、null 和 undefined。 目前仍然在下图中出现错误。有人会如何解决这个问题?

javascript-string-concatenation-behavior-with-null-or-undefined-values

在图片中,其中一个属性在说

TypeError: 无法读取未定义的属性

它甚至无法首先读取参数,应用未定义的过滤器等。

get copyFromDescription() {
    if (this.addressId == 0) {
        return 'Select';
    } else { return [this.apn, this.combinedAddress,this.addressType.addressTypeDescription].filter(Boolean).join('') }
}

数据值图

【问题讨论】:

    标签: angular typescript angular7


    【解决方案1】:

    使用

    .filter(val => !!val)
    

    布尔是一种类型

    并测试 addressType 是否未定义

    this.addressType && this.addressType.addressTypeDescription
    
    get copyFromDescription() {
        if (this.addressId == 0) {
            return 'Select';
        } else { return [this.apn, this.combinedAddress,this.addressType && this.addressType.addressTypeDescription].filter(val => !!val).join('') }
    }
    

    【讨论】:

    • 也发表了评论,由于某种原因,在我的数据模型中,地址类型存在,但没有进入新的对象数组,奇怪,我也试试这个
    • 另外,addessType 在我的模型中是可为空的成员,所以当我初始化模型时,没有该成员,它甚至不会显示,谢谢
    【解决方案2】:

    this.addressType 未定义。因此在尝试访问 addressTypeDescription 属性时无法获取值。

    布尔值是一种类型而不是测试。这对我来说似乎更合乎逻辑。

    get copyFromDescription() {
        if (this.addressId == 0) {
            return 'Select';
        } else { return [this.apn, this.combinedAddress,this.addressType.addressTypeDescription].filter(val => !!val).join('') }
    }

    但是你仍然会遇到需要测试的未定义错误。

    get copyFromDescription() {
        if (this.addressId === 0) 
            return 'Select';
        else if (this.addressType) return [this.apn, this.combinedAddress, this.addressType.addressTypeDescription]
          .filter(val => !!val).join('');
        else return [this.apn, this.combinedAddress] // you cannot use addressType here
          .filter(val => !!val).join('');
    }

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2022-11-17
      • 1970-01-01
      • 2019-02-15
      • 2018-11-08
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多