1

I have created few services in angular with provideIn as root using the following code.

@Injectable({
    providedIn: 'root'
}

This makes the service available to the whole application and I can import it anywhere I like. This seems very easy to do and is very intuative. But I was reading angular docs and came across Angular Dependency providers. I understand the concept behind it is to expose the service only to those components that need it. But I don't understand whats the use of this? We can make service available at root level and access where ever needed. Are there any optimisations benefit of configuring depenceny providers or is it merely because of security reasons or for any other reason?

Dhairya Tripathi
  • 197
  • 2
  • 14

2 Answers2

0

Which way you set your provider depends only on your use case. Many solutions are possible. You can find all the details here https://angular.io/guide/providers

KSoze
  • 141
  • 3
  • I was looking into more in-depth knowledge. The docs are great to help how to implement a feature but they don't tell why to use a method over others. – Dhairya Tripathi Feb 27 '21 at 12:46
0

So after asking the community and searching online I came to this conclusion.

Singleton Services

Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn to root on the service's @Injectable() decorator. This tells Angular to provide the service in the application root. This means we should use the root keyword as that performs some optimizations (before, you had to provide every service in some module. that meant that you had to take care that services were actually provided somewhere, and it also meant that unused services would still be packaged into your bundle (tree shaking)) and is recommended by the Angular design pattern. Keep in mind this method creates a single instance of that service.

Dhairya Tripathi
  • 197
  • 2
  • 14