Angular Service singleton constructor called multiple times
As you have declared the TestService as -
@Injectable({ providedIn: 'root'})
Which means you are adding to AppRoot module.
No need to add explicitly in the CoreModule
, so remove from providers of CoreModule
. Remove following -
providers: [ TestService ]
As you are adding the TestSevice
in CoreModule
which is already added in RootModule
that's the reason it constructor
getting called multiple times.
So use either of one from above.
@Injectable({ providedIn: 'root'})
- The
providedIn
withroot
option means, the service is available throughout the application assingleton
service. - It doesn't complain any error like
No provider for xxxservice
bcz ofprovidedIn
if you didn't added to providers list of any module. - If you do adding to the list will leads to creating a new instance of service, which will give you wrong results than expected.
NOTE : Please make sure to use the concept for better results.