1

What is the main benefit of creating constructor.

export class OrderHistoryComponent{

    constructor(private router:Router){}
    userState = 'Login';
    orders: Order[];

Can we work like

export class OrderHistoryComponent {

    router:Router){}
    userState = 'Login';
    orders: Order[];

Just creating the Object. Good understandable answers will be much appreciated.

Dan
  • 12,409
  • 3
  • 50
  • 87
Waseem Saeed
  • 85
  • 1
  • 13
  • you can also read [The essential difference between Constructor and ngOnInit in Angular](https://blog.angularindepth.com/the-essential-difference-between-constructor-and-ngoninit-in-angular-c9930c209a42) – Max Koretskyi Sep 11 '17 at 13:41

2 Answers2

1

Constructor is the default method of the class that is executed when the class is instantiated. Constructor basically ensures that all the class variables are properly initialized. Constructor is also used for dependency injection as follows:

constructor(heroService: HeroService) {
    this.heroes = heroService.getHeroes();
}
Peter
  • 10,492
  • 21
  • 82
  • 132
0

The reason is Dependency Injection, which is an important application design pattern:

constructor(heroService: HeroService) {
  this.heroes = heroService.getHeroes();
}

The constructor parameter type, the @Component decorator, and the parent's providers information combine to tell the Angular injector to inject an instance of HeroService whenever it creates a new HeroListComponent.

Check the link above to read more about it.

pzaenger
  • 11,381
  • 3
  • 45
  • 46