Understand providedIn options in angular services

gaurangdhorda

GaurangDhorda

Posted on October 25, 2020

Understand providedIn options in angular services

Angular CLI by defaults creates services in root level of app.module. That is declared in services @Injectable( ) decorator. like... { providedIn:'root' }. As of now angular provides different options of angular services like [a] root [b] any [c] platform. Understand each option using small diagram, and understand what level service is declared and object is live within which level of application.

You can support me

Alt Text

1. { providedIn: 'root' }

Alt Text

As You can seen above our root module is "app.module.ts", and providedIn: 'root', creates only one singleton object for entire child module and root module too. we simply inject services inside component and same root-level object instance is shared between each component.

2. { providedIn: 'any' }

Alt Text

As you can seen in above image, if services are created using providedIn: 'any', Then, each and every module have their own object state and each time new instance of service is created. Each root module has their own instance, and for each lazy module has their own instance.

3. { providedIn: 'platform' }

Alt Text

As you can seen in above image, providedIn: 'platform' is new provided by angular, and its creates services instance only once, and then share state in each library and each level down to component tree.

[ NOTE: ] We can also declare services inside modules providers:[] arrays. If services defined in providers:[] array then, services are not tree-shakable, and if we declare services as per images shown above, using @Injectable(), decorator then this pattern is tree shakable. Tree-Shakable is when you never reference and used services in any of your component, then final production build will not include that services.

You can support me

Alt Text

💖 💪 🙅 🚩
gaurangdhorda
GaurangDhorda

Posted on October 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related