首页 > 解决方案 > 如何处理未定义的参数?

问题描述

我正在开发一个角度应用程序。作为其中的一部分,我想处理某个参数未定义的情况。

我的代码

  myImage() {
    console.log('test')
    console.log(typeof(this.ahuObservables.on_off_status))
    this.myValue = this.myObservables.status
    console.log(typeof(this.myValue))
    if (this.myValue  == null)
    {
      console.log('undefined')
      this.ahuValue = 0
    }
    else{
    // do something
   }
 getDataRealTime()
  {
    console.log('Making a request')
    this.SocketService.socket_connection()
      .subscribe(
        (data1: any) => {
          console.log(data1)
          let data11 = JSON.parse(data1)
          this.myObservables = new My_Observables()
          this.myObservables.status = data11['status']
          console.log('variables parsed') 
        }
      )


  }

this.myObservables.status在 api 调用中分配。因此,当我的 api 不工作时,我希望我的myValue变量为 0。我尝试检查 null、未定义但如果 myObservables.status 未定义,我无法分配默认值。我的第二个 console.log 也没有打印任何内容安慰。有人可以帮我吗?

谢谢。

标签: javascriptangulartypescriptundefined

解决方案


您可以通过添加来检查 if 是否this.myValue有一个if(!this.myValue)值,然后 if 语句将仅在 this.myValue 的值为 0、空字符串、未定义或 null 时执行。

myImage() {
        console.log('test')
        console.log(typeof(this.ahuObservables.on_off_status))
        this.myValue = this.myObservables.status
        console.log(typeof(this.myValue))
        if (!this.myValue)
        {
// this part of the code will be executed if this.myValue is 0, empty string, undefined or null
          console.log('undefined')
          this.ahuValue = 0
        }
        else{
        // do something
       }

推荐阅读