我使用的是来自AlertModule的ng2-bootstrap。在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 { }发布于 2017-09-17 09:48:49
forRoot命名为静态函数有它们的自己的目的。它们用于应用程序级别的单例服务。
AlertModule中没有任何提供程序。当您调用forRoot时,它返回一个类型为ModuleWithProviders的对象,其中包括带有声明的AlertModule本身以及在AlertModule中使用的提供程序。
这就是在AlertModule - github源中所写的
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加法。
https://stackoverflow.com/questions/46262678
复制相似问题