我正在使用ng2-bootstrap
的AlertModule
。在imports
部分中,如果我只使用AlertModule
,我会得到错误Value: Error: No provider for AlertConfig!
。如果我使用AlertModule.forRoot()
,则应用程序正常。为什么?
我的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
名为静态功能具有其自己的目的。它们用于应用程序级别Singleton服务。
AlertModule
中没有任何提供商。当您调用forRoot
时,它将返回一个类型 modulewithProviders 的对象,其中包含 AlertModule
本身,并带有其声明,以及在AlertModule
中使用的提供程序。
这是 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] };
}
}
看,NgModule
的提供者部分被错过。这意味着,如果仅导入AlertModule
,则未提供providers
。但是,当您在其上致电forRoot
时,它将返回提供商AlertConfig
的AlertModule
。