When to use Angular’s forRoot() method

Chris House
Nov 6, 2017 · 2 min read

Problem: We needed to share a singleton language service across all lazy loaded modules. For a year, I saw the forRoot() method and simply ignored its power.

Explanation: The forRoot() method returns an NgModule and its provider dependencies.

In this example, we are sharing a service to keep up with a counter value. Each time any component increments the value stored in the counter service, I want to share this with all components.

The issue is when you try to introduce lazy loaded modules. Notice how the Lazy loaded component does not share the same counter value. When using eager loaded components only, the below example will work if you use a shared service, but notice how the lazy loaded component behaves. The lazy component gets its own instance of the service.

import { NgModule } from '';
import { CounterService } from './counter.service';
providers: [CounterService],
export class SharedModule {}

See plunker:

Solution: Call forRoot() in the AppModule and return a ModuleWithProviders in the sharedModule.


import { NgModule,ModuleWithProviders  } from '';
import { CounterService } from './counter.service';
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [ CounterService ]


import { NgModule } from '';
import { BrowserModule } from '';
import { SharedModule } from './shared/shared.module';import { AppComponent } from './app.component';
import { EagerComponent } from './eager.component';
import { routing } from './app.routing';
imports: [
declarations: [
bootstrap: [AppComponent]
export class AppModule {}

See Plunker:

Now the counter service is shared between eagerly loaded modules and lazy loaded modules.

Other recommended readings:

  • Note: I would not recommend putting shared services and shared directives in the same module. I have written this article as a reference for myself in the future.


For those who slack at noon

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store