Lemoncode / angular4-sample-app

MIT License
1 stars 0 forks source link

Constructor vs ngOnInit #4

Open crsanti opened 7 years ago

crsanti commented 7 years ago

In sample 01 Displaying Data the AppComponent is initializing the customers collection in the constructor() and customer in ngOnInit:

...
export class AppComponent implements OnInit {
  title = 'Displaying Data Demo';
  private customers: Customer[];
  customer: Customer;

  constructor() {
    this.customers = [
      new Customer('Jai', 'Sal', '25 June 1981',
      'http://vignette2.wikia.nocookie.net/disney/images/...'),
      new Customer('Fer', 'Sal', '25 November 1984'),
      new Customer('Lau', 'Sal', '04 March 2013')
    ];
  }

  ngOnInit() {
    this.customer = this.customers[0];
  }

but in sample 02 Displaying Collections customers assignation was moved to ngOnInit:

...
export class AppComponent implements OnInit {
  title = 'Displaying Collections Demo';
  customers: Customer[];

  constructor() {
  }

  ngOnInit() {
    this.customers = [
      new Customer('Jai', 'Sal', '25 June 1981',
      'http://vignette2.wikia.nocookie.net/disney/images/...'),
      new Customer('Fer', 'Sal', '25 November 1984',
      'http://vignette4.wikia.nocookie.net/disney/images/...'),
      new Customer('Lau', 'Sal', '04 March 2013',
      'https://vignette2.wikia.nocookie.net/pixar/images/...')
    ];
  }
}

How does it sound to keep the initialization only in one method? I think constructor() is more appropiated to initialize variables (later, given the right moment we could explain when use ngOnInit over constructor).

JaimeSalas commented 7 years ago

That is on purpose, the good practice in Angular is to get initialized using the lving hook events of component. Basically the constructor is only used for dependency injection.

crsanti commented 7 years ago

Ok, I got it ;)