【问题标题】:JSON property of Enum type does not like `null` checkEnum 类型的 JSON 属性不喜欢 `null` 检查
【发布时间】:2018-07-27 00:16:05
【问题描述】:

在我的 Angular 应用程序中,我有一个非常简单的 enum,名为 AlertType。我还有一个 API 响应对象,它的属性之一就是 enum 类型。如下:

export class ScanAlertModel {
    public alertId: string;
    public alertType: AlertType
}

我在某些情况下未设置此 alertType 属性。我正在尝试使用Jasmine 测试那些。在我的 Angular 应用程序中,为了能够为没有附加alerttype 的alert 过滤Array<AlertModel>,我只需应用如下过滤器即可:

this.scanAlerts.filter((a) => ((a.alertType === null)

这工作正常。但是,当我的 JSON 包含根本没有 alertType 的 ScanAlertModel 实体时,我尝试测试此过滤(作为更大功能测试的一部分)的测试无法正确过滤掉记录。

显然,这让我很困惑。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 已更改。谢谢

标签: json angular typescript enums null


【解决方案1】:

首先,如果alertType 有时不存在,则使用:? 将其声明为可选,如下所示:

export class ScanAlertModel {
    public alertId: string;
    public alertType?: AlertType;
}

您的过滤器并不总是有效的原因是,如果该属性未设置,则它不会严格等于null。

更好的检查是使用hasOwnProperty():

this.scanAlerts.filter(alert => !alert.hasOwnProperty('alertType'));

【讨论】:

  • 谢谢。我使用了“hasOwnProperty()”,这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2019-09-08
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
相关资源
最近更新 更多