DEV Community

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

Posted on

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.

Top comments (0)