Non-singleton services Non-singleton services angular angular

Non-singleton services


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.


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