[英]Why do I have to use AlertModule.forRoot() in imports of an NgModule?
我使用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 { }
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
它,它返回AlertModule
除了与供应商AlertConfig
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.