Initializing component class variables

I am starting in angular2 and I'm curious 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 have myHero initialized at the top, but I wonder what happens at the top, what should be inside the constructor and what happens inside ngOnInit?

Because, as far as I know, if it is at the top, it runs immediately, like the constructor, and ngOnInit?

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

thank

+4
source share
1 answer

The assignment of values ​​in the declaration and in the constructor is exactly the same, actually a compiled version of this:

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

There is:

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

vs. ngOnInit, , Hero -, ngOnInit.

+5

Source: https://habr.com/ru/post/1671645/


All Articles