简体   繁体   中英

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. 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?

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.

myfunctions.ts

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

component.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.

We should create service for methods which directly affects our components, such as HTTP request, etc.

As for the above method, I would create a util file and export the method from it.

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.

You have multiple choices:

  • In a service as a method.

  • in file Utils with export function calculatePercentage(...){...} as a static function.

  • In a class as a static method (It is the less recommanded )

There is no "BEST" way. Each methods have its adepts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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