Shared Modules and Service Providers

If you have created a shared module in your project, you might also have some services in it. And you might think, where is the best place to PROVIDE this service, so angular’s DI will create it’s instance.

If you decide to do the declaration in the SharedModule itself like this:

import { NgModule } from '@angular/core';
import { HelloService } from './hello.service';

  providers: [HelloService]
export class SharedModule {}

and import this SharedModule in other Modules, you will find that in each Module that imported this SharedModule, a seperate instance of the HelloService was created.

In order to avoid this, we will use the following notation

import { NgModule, ModuleWithProviders } from '@angular/core';
import { HelloService } from './hello.service';

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [HelloService]

Next, we will import this module in our AppModule, creating a single instance of the provided services

import { SharedModule } from './shared/shared.module';

  imports: [
export class AppModule {}

The above, will create a single instance of the provided services.

in other feature modules, in which the SharedModule is needed, we will just import it, without the use of the “forRoot” static method call.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s