DEV Community

Cover image for Angular's providedIn: "root". What if two lazy modules provided the same service?
Nick Raphael
Nick Raphael

Posted on

8 2

Angular's providedIn: "root". What if two lazy modules provided the same service?

Sheesh, I'm not sure about that title. Let's unpack it a little. The modern way for an angular application to register a singleton service class is using providedin.

https://angular.io/guide/singleton-services

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}
Enter fullscreen mode Exit fullscreen mode
@NgModule({
  ...
  providers: [UserService],
  ...
})
Enter fullscreen mode Exit fullscreen mode

What if we the module that provides the service is a lazy loaded module? Well, that service code will compile into the lazy loaded bundle for that module. Simple enough. But what if a second lazy loaded module also provides it? Where does angular (webpack?) put the service code? What bundle? Does it put it in the main bundle, in both lazy bundles or something else?

The answer is: something else. Angular is smart enough to realise there is a service that is shared between lazy modules. It puts that code in its own common module. Then whichever lazy module loads first, downloads the common module along with the lazy module. That way, the service isn't downloaded before it's needed and is still only downloaded once, despite being provided by two different lazy loaded routes.

Pretty clever.

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay