Sharing a service between modules in Angular

Today I want to speak about sharing an Angular Service between modules. First of all we need to create a new module that will be shared between other modules in our single page web application and which will provide a shared Service that will be accessed by the components of other modules.

import {ModuleWithProviders, NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import {MySharedService} from './services/my-shared.service';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [MySharedService]
    };
  }
}

As you can see the SharedModule provides a static forRoot() method that we will call in the our app.module file in order to register the MySharedService class. Below is the code snippet in which we register the module with it’s shared service.

@NgModule({
  declarations: [...],
  imports: [  ...
    SharedModule.forRoot(),
  ],
  providers: [
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

In the components of other modules we should only inject the shared service in the constructor and use it.

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test component.css']
})
export class TestComponent implements OnInit {
      constructor(private mySharedService: MySharedService){
	    	this.mySharedService.doSomething();    
   }

}