Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular 8中跨多个组件重用方法的最佳实践_Angular_Code Reuse - Fatal编程技术网

在Angular 8中跨多个组件重用方法的最佳实践

在Angular 8中跨多个组件重用方法的最佳实践,angular,code-reuse,Angular,Code Reuse,假设我有一个从两个数字返回百分比的方法: calculatePercentage(a, b) { return (((a - b) / b) * 100 * 2).toFixed(2); } 目前,我在component controller上有此方法。如何使其可跨多个组件重用?最佳做法是什么 我正在考虑将其作为一项服务使用:这是在Angular中使用的正确方法吗?您有多种选择: 在服务中作为一种方法 在文件Utils中,使用导出函数calculatePercentage

假设我有一个从两个数字返回百分比的方法:

  calculatePercentage(a, b) {
      return (((a - b) / b) * 100 * 2).toFixed(2);
  }
目前,我在component controller上有此方法。如何使其可跨多个组件重用?最佳做法是什么


我正在考虑将其作为一项服务使用:这是在Angular中使用的正确方法吗?

您有多种选择:

  • 在服务中作为一种方法

  • 在文件
    Utils
    中,使用
    导出函数calculatePercentage(…){…}
    作为静态函数

  • 在类中作为静态方法(它是


没有“最好”的方法。每种方法都有自己的专长

您有多种选择:

  • 在服务中作为一种方法

  • 在文件
    Utils
    中,使用
    导出函数calculatePercentage(…){…}
    作为静态函数

  • 在类中作为静态方法(它是


没有“最好”的方法。每种方法都有自己的专长,因此可以通过两种方式完成,一种是在服务中实现该功能,另一种是创建实用方法

我们应该为直接影响组件的方法创建服务,例如HTTP请求等

对于上面的方法,我将创建一个util文件并从中导出该方法

我希望这能澄清你的问题


对于这些问题,请使用不同的平台,在那里您可以获得建议,而不是StackOverflow,它旨在解决您的编程问题。

因此,可以通过两种方式完成,您可以在服务中实现该功能,也可以创建实用方法

我们应该为直接影响组件的方法创建服务,例如HTTP请求等

对于上面的方法,我将创建一个util文件并从中导出该方法

我希望这能澄清你的问题


对于这些问题,请使用不同的平台,在那里您可以获得建议,而不是StackOverflow,它旨在解决您的编程问题。

如果这些方法是幂等的,也不依赖于任何状态,那么我只需要一个单独的.ts文件,您可以从中导入函数

myfunctions.ts

export calculatePercentage = (a:number,b:number):string => {return (((a - b) / b) * 100 * 2).toFixed(2);}
import {calculatePercentage} from './myfunctions';

export class MyComponent {

  someMethod() {
      this.result = calculatePercentage(this.numa, this.numb);
  }
}
组件。ts

export calculatePercentage = (a:number,b:number):string => {return (((a - b) / b) * 100 * 2).toFixed(2);}
import {calculatePercentage} from './myfunctions';

export class MyComponent {

  someMethod() {
      this.result = calculatePercentage(this.numa, this.numb);
  }
}

如果这些方法是幂等的,并且不依赖于任何状态,那么我只需要一个单独的.ts文件,您可以从中导入函数

myfunctions.ts

export calculatePercentage = (a:number,b:number):string => {return (((a - b) / b) * 100 * 2).toFixed(2);}
import {calculatePercentage} from './myfunctions';

export class MyComponent {

  someMethod() {
      this.result = calculatePercentage(this.numa, this.numb);
  }
}
组件。ts

export calculatePercentage = (a:number,b:number):string => {return (((a - b) / b) * 100 * 2).toFixed(2);}
import {calculatePercentage} from './myfunctions';

export class MyComponent {

  someMethod() {
      this.result = calculatePercentage(this.numa, this.numb);
  }
}

谢谢大家!谢谢大家!