Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
Initialization of components class variables

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

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda