Skip to content

Constructor vs ngOnInit #4

@crsanti

Description

@crsanti

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions