【问题标题】:Javascript interpretes 0 as nullJavascript 将 0 解释为 null
【发布时间】:2018-06-17 09:14:38
【问题描述】:

我有一个spring 端点,它返回一个名为EnumStatoPagamentoEnum

后端枚举

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public enum StatoPagamentoEnum {

    DA_PAGARE(0),
    PARZIALMENTE_PAGATA(1),
    PAGATA(2);

    private int id;
    private StatoPagamentoEnum(int id) {this.id = id;}
    public int getId() {return id;}
}

后端端点

public @ResponseBody MyEnum getStatoPagamento(){
   StatoPagamentoEnum statoPagamento = myMethod();
   return statoPagamento;
}

这个端点由一个映射Enum的角度服务调用:

前端枚举

export enum StatoPagamentoEnum {
  DA_PAGARE = 0,
  PARZIALMENTE_PAGATA = 1,
  PAGATA = 2
}

前端调用端点

getStatoPagamento(idRichiesta: number): Promise<StatoPagamentoEnum> {
    const url = ...;
    return this.http.get<StatoPagamentoEnum>(url).toPromise();
  }

一切正常,除非我尝试读取 id 为 0 的枚举值;在这种情况下,角度服务似乎将 0 值读取为空。 javascript 是否有可能将 0 解释为空值?谢谢。

【问题讨论】:

  • ENUM 不应该从 1 开始吗?

标签: javascript spring angular enums


【解决方案1】:

javascript中的0被认为是null,你可以尝试这样声明你的枚举吗:

export enum StatoPagamentoEnum {
  DA_PAGARE = <number>0,
  PARZIALMENTE_PAGATA = <number>1,
  PAGATA = <number>2
}

【讨论】:

    【解决方案2】:

    0 在 JS 中是一个虚假值,因此您所说的 Angular 服务很有可能在某处看起来像

    if(!theThingThatYouAreTalkingAbout)

    无论theThingThatYouAreTalkingAbout0 还是null(或空字符串,或undefined),其行为方式都相同。

    【讨论】:

    • JS 需要使用 if(theThingThatYouAreTalkingAbout === 0)。 Triple = 检查类型是否为数字
    • 这是两个独立的语句。 :D === 确实进行了完全等效检查,但是 OP 在这里描述的问题是因为 JS 根本“不需要”使用它! :)
    【解决方案3】:

    在我的情况下,问题是线

    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    

    这强制将枚举映射为数组,因此端点将返回枚举中元素的位置,而不是它的 id。

    1. 我可以用

      替换该行

      @JsonFormat(shape = JsonFormat.Shape.OBJECT)

    在这种情况下,端点将返回包含元素 id 的 o json 对象,即{"id":1}

    1. 我可以完全删除注释,在这种情况下,端点将返回元素 id,即"DA_PAGARE"

    这两种解决方案现在都适用于我。 0 -&gt; null 隐式转换的 javascript 问题仍然存在。

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2011-05-01
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多