How to use Shared Modules with Angular 2

This demo assumes that you already have an angular 2.x app bootstrapped.

First lets create our shared module called “SharedModule“.

app/shared/shared.module.ts

import { CommonModule } from '@angular/common';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
...

Now let us import some services and components as well. Let us assume we have created a service called “httpService” and a custom component called ‘loaderComponent‘.

import { CommonModule } from '@angular/common';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { loaderComponent } from './loader.component';
import { httpService } from './http.service';
...

Next is to create the module itself.

 

@NgModule({
    imports: [ 
        CommonModule, FormsModule, HttpModule
    ], // import modules
    declarations: [
        loaderComponent
    ], // declare components
    exports: [
        CommonModule, FormsModule, HttpModule, loaderComponent
    ] // all the modules and components that are needed to be shared across modules.
})

export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [ httpService ] // all the services that are needed to be shared across modules.
        }
    }
}

 

Since services are singletons, that means services should be declared only once. So the most crucial point to note here is  “ModuleWithProviders”. We define a static method called “forRoot()” that returns ab object of type “ModuleWithProviders“.

 

Now in our main module, import “SharedModule” with forRoot() and for all other lazy loaded modules, just import “SharedModule“.

 

app/app.modules.ts

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

@NgModule({
    ...
    imports: [
        ...
        SharedModule.forRoot()
    ]
})

 

For all the other lazy loaded modules,

 

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

@NgModule({
    ...
    imports: [
        ...
        SharedModule
    ]
})