简体   繁体   English

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

[英]Best practices for reusing methods across multiple components in Angular 8

Let's say I have a method that returns the percentage from two numbers:假设我有一个从两个数字返回百分比的方法:

  calculatePercentage(a, b) {
      return (((a - b) / b) * 100 * 2).toFixed(2);
  }

Currently, I have this method on component controller.目前,我在组件 controller 上有这种方法。 How do I make it reusable across multiple components?如何使其可跨多个组件重用? What is the best practice?最佳做法是什么?

I am thinking to use it as a service: is that the right way to do it in Angular?我正在考虑将其用作服务:在 Angular 中这样做是否正确?

If the methods are idempotent and also do not rely on any state then I would just have a separate.ts file where you can import the functions from.如果这些方法是幂等的并且也不依赖于任何 state 那么我将只有一个单独的.ts 文件,您可以从中导入函数。

myfunctions.ts我的函数.ts

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

component.ts组件.ts

import {calculatePercentage} from './myfunctions';

export class MyComponent {

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

So it can be done in two ways, either you can implement that function inside the service or create utility methods.所以它可以通过两种方式完成,您可以在服务内部实现 function 或创建实用程序方法。

We should create service for methods which directly affects our components, such as HTTP request, etc.我们应该为直接影响我们组件的方法创建服务,例如 HTTP 请求等。

As for the above method, I would create a util file and export the method from it.至于上述方法,我会创建一个 util 文件并从中导出方法。

I hope this clears your question.我希望这能解决你的问题。

And for such questions, please use different platforms where you can get suggestions instead of StackOverflow which is intended to solve your programming issues.对于此类问题,请使用不同的平台来获得建议,而不是使用旨在解决您的编程问题的 StackOverflow。

You have multiple choices:您有多种选择:

  • In a service as a method.在作为方法的服务中。

  • in file Utils with export function calculatePercentage(...){...} as a static function.在文件Utilsexport function calculatePercentage(...){...}作为 static function。

  • In a class as a static method (It is the less recommanded )在 class 作为 static 方法(这是较少推荐

There is no "BEST" way.没有“最佳”方式。 Each methods have its adepts每种方法都有其高手

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM