If you use providers in service it will instantiate everytime when component get loaded, but if I use it in app.module, does service get instantiate everytime when component uses?
In angularJS (1.x) it’s working like a Singleton. Means there is only one instance which is shared by all components.
I don’t know Angular (2.x and up) but I strongly belief it’s working the same there. Please anyone correct me if this is wrong.
Afaik you will get an instance per module use, so if you use the service in 2 modules you would have 2 instances. If you put the service in its own module (not app. module) then you will have only one instance across the app.
No it doesn't. In Angular (2.x and up) if you use it in app.module, service will be instantiated only once and it will be used by all components that belongs to that module.
Speaking about Angular 2+ here:
Generally services are singletons, especially if you've only declared it as a provider in one place (module or component).
However, Angular does feature a hierarchical injector system meaning each component has its own injector. These injectors can also have parent injectors. When an injector tries to resolve a provider, it will first look in its provider list. If its list defines the provider, the injector will use that one. Otherwise it will recursively traverse back up the injector hierarchy until it finds a reference.
Given that, there can be multiple instances of the same service in your app. For example if you were to declare a provider on a component class, every instance of that component would get its own service.
@Component({ selector: 'my-component', providers: [MyService] }) export class My component { constructor(service: MyService) { // service is unique for every component } }Generally it's not prudent to declare providers on components. It becomes really difficult to track down bugs when there are multiple instances of a service in play.