angulartypescripttypescript1.6

Angular2 Typescript how to refactor code out of Component constructor


The Angular 2 guide has this example with a constructor in a

component://Typescript
class DisplayComponent {
  myName: string;
  names: Array<string>;
  constructor() {
    this.myName = "Alice";
    this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];
  }
} 

From https://angular.io/docs/ts/latest/guide/displaying-data.html#Create-an-array (retrieved 2015-10-30)

Consider this is a simple example, but often in real life, my constructors grow bigger and bigger. Also I have sometimes the need to use the same logic several places, and not only on construction time.

My first reaction was to create a separate function and call that on the instance. But Typescript does not allow this, since the instance is not created when the constructor runs.

My question is: How do I extract lines of code from the constructor and pull it out into a separate function?


Solution

  • Is this what you are looking for ?

    class MyClass {
    
        constructor( ) {
            MyClass.saySomething()
            this.sayItAll()
        }
    
        public static saySomething(){
            console.log('Hi')
        }
    
        public sayItAll(){
             console.log('Hello')
             MyClass.saySomething()
        }
    }
    

    So you can also call MyClass.saySomething() from an other class without an instance of MyClass ?