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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With