While coding an app with Angular 2 and multiple calculation services I faced the following questions:
This is a snap of the class, that provides me multiple calculation methods and is instantiated on application level:
@Injectable()
export class FairnessService {
constructor(){}
private static calculateProcentValue(value: number, from: number): number {
return (Math.abs(value) / Math.abs(from)) * 100;
}
public static calculateAllocationWorth(allocation: Allocation): number {
...
}
}
Thanks for helping.
They do make sense in Angular services. There are situations where we can't / don't actually need to use an instance of the service, and we can't / don't want to make a new dependency on it, we only need access to the methods our service carries. Here static members come in.
The example of using the static method defined in the service:
import { FairnessService } from './fairness.service';
export class MyComponent {
constructor() {
// This is just an example of accessing the static members of a class.
// Note we didn't inject the service, nor manually instantiate it like: let a = new A();
let value = FairnessService.calculatePercentValue(5, 50);
let value2 = FairnessService.calculatePercentValue(2, 80);
console.log(value); // => 10
console.log(value2); // => 2.5
}
}
For more information, it's explained well on: http://www.typescriptlang.org/docs/handbook/classes.html