为什么我必须在ngmodule的导入中使用artermodule.forroot()



我正在使用ng2-bootstrapAlertModule。在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时,它将返回提供商AlertConfigAlertModule

最新更新