【问题标题】:What's the best way to avoid many if statements in Angular component to call specific function?避免Angular组件中的许多if语句调用特定函数的最佳方法是什么?
【发布时间】:2020-02-15 21:43:28
【问题描述】:

我正在 Angular 7 中创建一个温度转换应用程序,在我的 formGroup 中,我有一个输入/输出值,以及 2 个多选,用户可以在其中选择一个温度单位“从”和“到”进行转换(摄氏度、华氏或开尔文)。

当用户在我的组件中提交表单时,我会得到输入数据

submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
  }

我认为只是添加 if 语句来调用将进行转换的函数,但现在查看我拥有的所有 if 语句似乎很多而不是一个好的设计。

if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
        this.celsiusToFahrenheitConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
      this.celsiusToKelvinConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
      this.celsiusToRankineConversion ();
}

如果是华氏,如果是开尔文,如果是兰金等。 如果我想在功能中添加不同类型的单位怎么办? 有什么更好的方法?

提前致谢

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我认为最简洁的处理方法是使用 switch 语句。没有比这更简单的了,我个人也讨厌它,但有时真的没有办法绕过它。

    switch(this.inputType) {
      case 'Celsius':
        switch(this.targetUnit) {
          case 'Fahrenheit':
            this.celsiusToFahrenheitConversion();
            break;
          case 'Kelvin':
            this.celsiusToKelvinConversion();
            break;
          case 'Rankine':
            this.celsiusToRankineConversion();
            break;
        }
        break;
      case 'Fahrenheit':
        break;
      case 'Rankine':
        break;
      case 'Kelvin':
        break;
    }
    

    但是!这是一个数学转换。 F° 到 C° (32°F − 32) × 5/9,F° 到 Kelvin 是 (32°F − 32) × 5/9 + 273.15,F° 到 Rankine 是 32°F + 459.67 等等。哪里有数学,哪里就有系统。我的方法是创建一个转换表 - 一个对象,并将表单值用作查找值。例如:

    const magicalLookupTable = {
      celsius: {
        fahrenheit: () => {
          /** Implementation */
        },
        kelvin: () => {
          /** Implementation */
        }
      },
      fahrenheit: {
        celsius: () => {
          /** Implementation */
        },
        kelvin: () => {
          /** Implementation */
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      当我看到这个时,我看到了针对函数值设置的复合键。

      表示这个想法的一种方法是使用一个典型的对象,其中键是复合词,它们映射到特定的函数:

      const conversionFunctions = {
          'celsius-fahrenheit': this.celsiusToFahrenheitConversion,
          'celsius-kelvin': this.celsiusToKelvinConversion,
          'celsius-rankine': this.celsiusToRankineConversion
      };
      
      const key = `${this.inputUnit.toLowerCase()}-${this.targetUnit.toLowerCase()}`;
      const convert = conversionFunctions[key];
      
      convert();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2019-08-23
        • 2021-03-08
        相关资源
        最近更新 更多