How can I differentiate shared service from other service in angular 6+?

348 Views Asked by At

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?

2

There are 2 best solutions below

0
tomek550 On

You can provide a service inside a component decorator, which makes it available only locally to that component.

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  providers: [MyService]
})
0
Никита Середа On
  1. if u add service to app.module.ts - u can use it in every component and u will get save data everywhere
  2. if u include service in @Component decorator in providers block - this service will destroy automatically
  3. 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