Here is the current file situation:
AppService
AppModule
AModule
AComponent
BModule
BComponent
Regarding the Service
, I have noticed that Angular will create two separate instances of the service if it is injected into two components, meaning the data is not shared. However, when the Service
is injected in the AppModule
as a Singleton Pattern
, the data is shared among all components.
What happens when the Service
is injected in both AModule
and BModule
? I initially assumed that the result would be the same as injecting in a component, but it turns out to follow the Singleton Pattern
.
Why is this the case? Even though the Service
was injected into two different modules, Angular seems to generate a single instance of the service. Can someone help me understand why? Thank you.
You can view the StackBlitz demo at angular-service-inject-modules
I have created a demo that outputs random numbers to demonstrate the behavior of the Singleton Pattern
with the service.