Reputation: 6217
What is the different between this:
bootstrap(AppComponent, [HeroService]);
And this:
@Component({
selector: 'test',
providers: [HeroService]
})
Upvotes: 4
Views: 150
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
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
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