5

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

DI in angular 2 creates a Singleton instance. If we use new keyword instead of using DI, will it also create a Singleton instance? Just being curious.
@barnes no, new always just creates a new instance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.