I understand there have been some changes in Angular 6 with the way singleton services have to be created. I have an Auth Service that needs to be constructed once for each component that accesses it. I set the provider to root for the service:
@Injectable({
providedIn: 'root'
})
And in my app.module.ts file, I set AuthService as one of my providers in NgModule. However, whenever I route between different components that use the Auth service, it creates a new instance of the Auth Service (clearing data from the first time it was called). How do I ensure that the Auth Service is only instantiated once, and then access that instance among different components?
The main objective of angular services is to share data across Angular application. Practically an angular service can be shared between all the components or can be limited to some component. Hence Angular service can be a singleton as well as non-singleton in nature.
The forRoot() method creates an NgModule that contains all the directives, the given routes, and the Router service itself. The forChild() method creates an NgModule that contains all the directives and the given routes, but does not include the Router service.
A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.
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.
To avoid any other confusion you can create singletons in two ways, just as stated in the docs (singleton-services):
@Injectable({providedIn: 'root'})
.{providedIn:'root'}
.In my case singleton services did not work when using JIT (normal ng build / ng serve). For me it only worked when using AoT (ng build --aot / ng serve --aot).
That's the default behaviour of adding providedIn to the service level. As per Docs
providedIn here tells Angular that the root injector is responsible for creating an instance of the HeroService. Services that are provided this way are automatically made available to the entire application and don't need to be listed in any module.
in your case just remove the providedIn: 'root'
and have only under provides in the module.ts. Refer the following answer.
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