I use to hear the term that uses shared services for sharing data between non-relevant components in angular. But every service is a shared service or not? if it is, then how it is different from shared services?
How can I differentiate shared service from other service in angular 6+?
348 Views Asked by Muhammad Arqam At
2
There are 2 best solutions below
0
On
- if u add service to app.module.ts - u can use it in every component and u will get save data everywhere
- if u include service in @Component decorator in providers block - this service will destroy automatically
- if u have modules A, B & C and some service included in B. When u will use lazy loading components in module C sometimes will not have service from module B (if refresh page on component who rendered from module C)
so difference between shared and normally services - where they was included.
app.module - shared every where
module B - shared only for child modules who was included in module B.
component providers (@Component({providers: [...]})) - only locally and will be destroed with component
You can provide a service inside a component decorator, which makes it available only locally to that component.