user233232
user233232

Reputation: 6217

Angular: what is the difference between declaring a service in a component and the bootstrap process

What is the different between this:

bootstrap(AppComponent, [HeroService]);

And this:

@Component({
  selector: 'test',
  providers: [HeroService]
})

Upvotes: 4

Views: 150

Answers (3)

Sasxa
Sasxa

Reputation: 41314

When you declare provider in bootstrap it will be available to all components in your application. If you declare it inside the component it will be available only inside that component.

Make sure you don't include it in both places or you will create new instance inside the component and overwrite the instance from bootstrap.

Upvotes: 1

garethdn
garethdn

Reputation: 12373

When you pass HeroService as a dependency to the bootstrap method then the HeroService behaves as a singleton - with one single instance of the class available throughout your application.

Passing it in the providers array will create a new instance of the service.

Take a look at this article for a detailed explanation of dependency injection in Angular 2.

Upvotes: 1

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

Reputation: 658263

If you add it only to bootstrap() you get a singleton, if you add it to the component you get a new instance for each component instance. If you add it to both then it depends on where you inject it. Angular2 has a hierarchical DI. It searches upwards for a provider, the first it founds is returned.

See also http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

Upvotes: 2

Related Questions