Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of components class variables [duplicate]

I'm starting out in angular2, and I'm wondering about this code

export class HeroesComponent implements OnInit {

    // Version 1
    myHero: Hero = new Hero('Superman', 'Clark Kent');

    // Version 2, 3
    // myHero: Hero;

    constructor() {
        // Version 2
        // this.myHero = new Hero('Superman', 'Clark Kent');
    }

    ngOnInit() {
        // Version 3
        // this.myHero = new Hero('Superman', 'Clark Kent');
    }

}

Right now I've got myHero initialized at the top, but I'm wondering, what goes at the top, what should be inside the constructor and what goes inside ngOnInit?

Because as far as I know, if it's at the top, it's executed straight away, same with the constructor, and ngOnInit?

So what's the difference, and what's correct?

Thank you

like image 878
user3623300 Avatar asked Mar 06 '17 21:03

user3623300


1 Answers

Assigning the values in declaration and in the constructor is exactly the same, in fact the compiled version of this:

class HeroesComponent implements OnInit {
    myHero: Hero = new Hero('Superman', 'Clark Kent');
}

Is:

var HeroesComponent = (function () {
    function HeroesComponent() {
        this.myHero = new Hero('Superman', 'Clark Kent');
    }
    return HeroesComponent;
}());

As for that vs. ngOnInit, it depends whether or not the constructor of Hero depends on anything that might not be ready before ngOnInit is fired.

like image 197
Nitzan Tomer Avatar answered Oct 18 '22 18:10

Nitzan Tomer