Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
f1vlad Avatar asked May 11 '26 21:05

f1vlad


2 Answers

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);
  }
}
like image 176
Igor Avatar answered May 14 '26 13:05

Igor


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

like image 32
Wandrille Avatar answered May 14 '26 12:05

Wandrille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!