Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to use AlertModule.forRoot() in imports of an NgModule?

I'm using AlertModule from ng2-bootstrap. In the imports section if I just use AlertModule I get the error Value: Error: No provider for AlertConfig!. If I use AlertModule.forRoot() the application works fine. Why?

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {AlertModule} from 'ng2-bootstrap/ng2-bootstrap';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule, 

   // AlertModule, /*doesn't work*/
    AlertModule.forRoot() /*it works!*/
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
like image 229
Nishant Avatar asked Sep 17 '17 09:09

Nishant


1 Answers

forRoot named static functions have their own purpose. They are used for application level singleton services.

AlertModule does not have any providers in it. When you call forRoot, it returns an object of type ModuleWithProviders which includes the AlertModule itself with it's declarations and also providers which are used in AlertModule.

This is what is written in the AlertModule - github source

import { CommonModule } from '@angular/common';
import { NgModule, ModuleWithProviders } from '@angular/core';
import { AlertComponent } from './alert.component';
import { AlertConfig } from './alert.config';

@NgModule({
   imports: [CommonModule],
   declarations: [AlertComponent],
   exports: [AlertComponent],
   entryComponents: [AlertComponent]
})
export class AlertModule {
   static forRoot(): ModuleWithProviders {
     return { ngModule: AlertModule, providers: [AlertConfig] };
   }
}

Look that providers section of NgModule is missed. This means if you import only AlertModule the providers are not provided. But when you call forRoot on it, it returns the AlertModule addition with provider AlertConfig.

like image 78
Suren Srapyan Avatar answered Nov 19 '22 00:11

Suren Srapyan