Skip to content
Advertisement

Static Methods and Angular 2 Services in JavaScript ES6

While coding an app with Angular 2 and multiple calculation services I faced the following questions:

  1. When do I use static in a Angular service provided on application level? Is that nonsense?
  2. How does a static method reflect on performance? Lets say a couple hundret objects call at the same time the same static method. Is this method instantiated more than once?

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.

Advertisement

Answer

  1. Static methods of a class, unlike instance methods, belong to (are visible on) the class itself (not an instance of it). They do not depend on the instance members of a class and will usually take input from the parameters, perform actions on it, and return some result. They act independently.

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
    }
}
  1. Static methods have no impact on the performance. As we’ve ascertained above, they do not depend on any instance of the class, and invoking those methods will in no way instantiate the class.

For more information, it’s explained well on: http://www.typescriptlang.org/docs/handbook/classes.html

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement