Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to create constructor in Angular2 typescript?

Here are some example constructors from the Angular 2 docs:

export class AppComponent implements OnInit {
    title = 'Tour of heroes';
    heroes: Hero[];
    selectedHero: Hero;

    constructor(private heroService: HeroService) { }

    getHeroes() {
        this.HeroService.getHeroes().then(heroes => this.heroes = heroes);
    }
}

and...

class Car {
    constructor(engine, tires, doors){
        this.engine = engine;
        this.tires = tires;
        this.doors = doors;
    }
}

I don't understand Why and When to create a constructor() in angular 2 /typescript (I've read the official documentation where they create a constructor for Dependency Injection and for Services).

like image 427
Sarvesh Yadav Avatar asked May 18 '16 08:05

Sarvesh Yadav


2 Answers

Constructors define which parameters to provide when instantiate your objects. In TypeScript, you can also add modifiers like private or public to define in the same time class properties and set their values with the provided ones.

For example:

class Car {
  constructor(private engine:string, private tires:string, private doors:number){
  }
}

is similar to:

class Car {
  constructor(engine:string, tires:string, doors:number){
    this.engine = engine;
    this.tires = tires;
    this.doors = doors;
  }
}

In Angular2 constructors are used for dependency injection. The associated decorator (@Component or Injectable) collects metadata (types or hints within @Inject) to determine what to provide to the object to instantiate.

Be aware that constructors aren't part of the component lifecycle. Properties can be set later by Angular2 at this level...

like image 71
Thierry Templier Avatar answered Oct 16 '22 09:10

Thierry Templier


Controller constructors are mainly used for dependency injection / services as you mentioned and also (in my apps) for initializing complex default values based off the services themselves. Since the constructor runs before the controllers template is initialized - no variables will be rendered accurately, hence the need for ngOnInit and other similar methods. These 'bootstrap' methods should be used to perform the normal 'constructing' duties so the template/view can access the data.

Regarding service constructors, a few of mine use the constructor normally and initialize various parts of the service based off existing user data as they act a lot more like standard classes.

These answers will be of help:

  • Difference between Constructor and ngOnInit
  • Angular 2 Component Constructor Vs OnInit
like image 44
SamV Avatar answered Oct 16 '22 11:10

SamV