Nis*_*ant 5 typescript angular
我正在使用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 { }
Run Code Online (Sandbox Code Playgroud)
forRoot命名静态函数有自己的用途。它们用于应用程序级别的单例服务。
AlertModule里面没有任何提供者。当您调用 时forRoot,它会返回一个ModuleWithProviders类型的对象,该对象包括AlertModule自身及其声明以及在AlertModule.
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] };
}
}
Run Code Online (Sandbox Code Playgroud)
看NgModule错过了提供者部分。这意味着,如果你只导入AlertModule了providers不提供。但是当你调用forRoot它时,它会返回AlertModule与 provider的相加AlertConfig。
| 归档时间: |
|
| 查看次数: |
1365 次 |
| 最近记录: |