How to provide a service in Angular root module
Providing services in the root module ensures they are available throughout the entire application as singletons, which is essential for shared state and global functionality.
As the creator of CoreUI, a widely used open-source UI library, I’ve configured root-level services in numerous Angular applications over 25 years of development.
From my expertise, the most modern approach is using providedIn: 'root' in the service decorator, which automatically provides the service at the root level.
This creates tree-shakable services and ensures optimal bundle size.
Use providedIn: 'root' in the service decorator to provide services at root level.
@Injectable({
providedIn: 'root'
})
export class GlobalService {
private data = new BehaviorSubject(null)
getData() { return this.data.asObservable() }
}
Here providedIn: 'root' automatically registers the service with the root injector, making it available throughout the application as a singleton. This is preferred over adding services to the providers array in AppModule because it enables tree-shaking - if the service isn’t used anywhere, it won’t be included in the final bundle.
Best Practice Note:
This is the same service provision pattern we use in CoreUI Angular components for global services and shared state management.
Use providedIn: 'root' for services that need to be singletons across the application, and consider using providedIn: 'any' for services that should have separate instances in lazy-loaded modules.



