打字稿/角度的IF语句

时间:2019-11-23 16:27:39

标签: javascript angular typescript if-statement

我正在尝试根据用户输入获得正确的弹出消息。

如果用户是“所有者”,则必须填写所有标记为“所有者”的项目。如果没有,单击“提交”时应该显示警告消息。

我在下面写下了要遍历每个项目的内容,并且该项目的所有者等于Con且值是空的,它应该给我警告消息。如果他们已填写,则应该是确认消息。

但是,以下内容没有给我我所需的结果。无论发生什么,即使已填充该值,我也始终会弹出警告消息。

  isValuePopulated() {  
    let attrData = this.attributes.attrData;
    let isAttributeCompleted = true;
    attrData.forEach(item=>{
      if(item.owner==='Con' && commonFunctions.isEmptyString(item.value)){
        isAttributeCompleted = false;
      }}
      );
    if (isAttributeCompleted){
      this.showErrorInfoPopUp('All correct!!!!', 'Confirmation', true);      
    } else {
      this.setErrorPopUpButtonStatus(true, false, true);
      this.showErrorInfoPopUp('Are you sure you want to continue?', 'Warning', true);
    }
  }

编辑: 感谢到目前为止的评论,我已经删除了commonFunctions.isEmptyString(item.value))的建议。但是我认为错误归结于asyc的循环(也提到了)。但是,由于这是我的新手,所以我不确定如何解决此问题。我的第一个想法是使用两种方法,并在各个项目之间进行一个循环,然后将值推入另一种确定弹出窗口的方法。但是,在尝试构建时,我始终收到“预期表达式”错误消息。

  isValuePopulated() {  
let attrData = this.attributes.attrData;
let isAttributeCompleted = true;
attrData.forEach(item=>{
  if(item.owner==='Con' && !item.attributeValue){
    isAttributeCompleted = false;  
      }}
      );
      this.typeOfPopUp(isAttributeCompleted )
  }

  typeOfPopUp(isAttributeCompleted ){

  if (isAttributeCompleted ){
    this.setErrorPopUpButtonStatus(true, false, true);
    this.showErrorInfoPopUp('All correct!!!!', 'Confirmation', true);      
  } else {
    this.setErrorPopUpButtonStatus(true, false, true);
    this.showErrorInfoPopUp('Are you sure you want to continue?, 'Warning', true);
  }
}

3 个答案:

答案 0 :(得分:2)

尽管@Jérôme的观点是正确的,但您面临的问题是因为您希望异步代码块同步运行。 您可以改用简单的for-of循环。

-Djsse.enableSNIExtension=false

答案 1 :(得分:1)

正如评论所说,将您的函数isEmptyString()替换为!item.value。 如果item.value为NOT,则条件if(item.value)的计算结果为true:

  • 未定义
  • 空字符串
  • NaN
  • 0
  • false

Source

答案 2 :(得分:0)

感谢您的建议。我没有意识到我原来使用的循环是异步的,也没有意识到有替代的非异步循环解决方案 以下代码有效:

  isValuePopulated() {  
    let attrData = this.attributes.attrData;
    let attributeCompleted: boolean = true;
    for (const item of attrData){
      if(item.owner==='Con' && !item.value){
        attributeCompleted = false;
      }

    }
    if (attributeCompleted){
      this.setErrorPopUpButtonStatus(true, false, true);
      this.showErrorInfoPopUp('All correct!!!!', 'Confirmation', true);      
    } else {
      this.setErrorPopUpButtonStatus(true, false, true);
      this.showErrorInfoPopUp('Are you sure you want to continue?', 'Warning', true);
    }
  }