1

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?

3
  • You can create a instance function and call it from the constructor. Maybe i am not getting what you meant here. Commented Oct 30, 2015 at 13:18
  • @Chandermani please add an example as an answer. What you describe is exactly what I am looking for :) Commented Oct 30, 2015 at 13:47
  • Wouldn't it be better to put this code in ngOnInit? Commented Jan 26, 2016 at 15:40

1 Answer 1

2

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 ?

Sign up to request clarification or add additional context in comments.

2 Comments

yes, this is an example of calling a static method. Can you also update the example with an instance example (since I want to write properties on the instance).
Obviously you need to get an instance of MyClass to call the method sayItAll()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.