BubbleTea
BubbleTea

Reputation: 629

Angular2 - calling constructor() vs new keyword to create an object?

I went through the Angular2 tutorial and i couldn't really understand the difference between something like:

constructor(private _heroService: HeroService) { } 

and creating an object such as

var _heroService: HeroService = new HeroService();

could you clarify?

Upvotes: 5

Views: 13394

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657536

The constructor

constructor(private _heroService: HeroService) { } 

is executed when

new SomeComponent();

is executed, where the constructor defines which parameters need to be passed to new Xxx(...). For example:

new SomeComponent(new HeroService);

If a new instance is created by Angular new Xxx(...) is executed by Angulars DI, It figures out which parameters to pass automatically from the constructor.

If no constructor is defined the default constructor

constructor(){} 

is automatically added to the class.

Upvotes: 2

Sasxa
Sasxa

Reputation: 41284

Declaring an object as constructor argument makes it part of Dependency Injection system. It's typically used with services and insures that services are singletons.

Instantiating an object with new keyword is used to create objects that are not injectable, typically data models. It's also sometimes used when testing (simple) services.

Upvotes: 3

Related Questions