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?
In this case, service is a non-singleton nature. It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component. Service is being destroyed along with the component.
A singleton service is a service for which only one instance exists in an application. For a sample application using the app-wide singleton service that this page describes, see the live example / download example showcasing all the documented features of NgModules.
There are two types of services in angular: Built-in services – There are approximately 30 built-in services in angular. Custom services – In angular if the user wants to create its own service he/she can do so.
By default, this decorator has a providedIn property, which creates a provider for the service. In this case, providedIn: 'root' specifies that Angular should provide the service in the root injector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With