Reputation: 2453
I have a file upload component that I'm using several times in one view. I have a service that manages the metadata about each uploading file. When I add files to one component, all the components start updating instead of just the one that had files added.
Is there a way to have a new instance of the service attached for each component that is being displayed?
Upvotes: 31
Views: 19965
Reputation: 3022
You have to provide the service in the relevant component only, then it's only available to that particular component, and its children only. If you used the service in the Module, then it's available in the root level of the application.
@Component({
selector: 'app-villains-list',
templateUrl: './villains-list.component.html',
providers: [ VillainsService ]
})
By providing VillainsService in the VillainsListComponent metadata and nowhere else, the service becomes available only in the VillainsListComponent and its sub-component tree. VillainService is a singleton with respect to VillainsListComponent because that is where it is declared. As long as VillainsListComponent does not get destroyed it will be the same instance of VillainService but if there are multilple instances of VillainsListComponent, then each instance of VillainsListComponent will have its own instance of VillainService.
https://angular.io/guide/hierarchical-dependency-injection
Upvotes: 19
Reputation: 156459
According to the docs:
Providing the service at the component level ensures that every instance of the component gets its own, private instance of the service.
So rather than listing the service in the providers
of the application module, try listing it in a lower-level component definition.
Upvotes: 33