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 { }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With