Search code examples
angularoptimizationdesign-patternsdependency-injectionangular-dependency-injection

Why set up Dependency providers in angular?


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?


Solution

  • 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.