如何在Angular中处理空值

时间:2018-03-29 18:24:03

标签: angular

我正在向Angular发送数据,但记录的值(关闭日期)之一为null。如何在Angular中处理此问题,以便如果value为null,则更改为--

  getDetails() {
    this.myService.getFlowerDetails(this.flowerId, this.flowerName).subscribe(
      res => {
        this.flower = res;
        if(this.flower !== undefined){
          this.flowerName = this.flower.flowerName;
          this.flowerId = this.flower.flowerId.toString();
          this.flowerCategory = this.flower.flowerCategory;
          this.recordCreateDate = this.flower.recordCreateDate.toString();
          this.recordClosedDate = this.flower.recordClosedDate.toString(); // this is null in the backend
        }
        else{
          this.flowerName = "--";
          this.flowerId = "--";
          this.flowerCategory = "--";
          this.recordCreateDate = "--";
          this.recordClosedDate = "--";
        }
      }, er => {
    this.throwError = er;
});

我收到以下错误。这不是整个堆栈跟踪(不确定是否需要)

TypeError
​
columnNumber: 17
​
fileName: "http://localhost:4200/main.bundle.js"
​
lineNumber: 1738
​
message: "_this.flower.recordClosedDate is null"

2 个答案:

答案 0 :(得分:5)

如果||是假的(this.flower.recordClosedDateundefined,空字符串,零,则null运算符可用于设置默认值:

this.recordClosedDate = (this.flower.recordClosedDate || "--").toString();

答案 1 :(得分:0)

普通的?:三元运算符怎么样:

this.recordClosedDate = this.flower.recordClosedDate !=null ?  this.flower.recordClosedDate : "--"