Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-singleton services

Tags:

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?

like image 459
Justin Young Avatar asked Apr 07 '17 16:04

Justin Young


People also ask

What is non singleton service in Angular?

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.

What is a singleton service?

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.

What are the types of services in Angular?

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.

What is providedIn in Angular service?

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.


1 Answers

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.

like image 193
StriplingWarrior Avatar answered Sep 22 '22 03:09

StriplingWarrior