繁体   English   中英

为什么我必须在导入NgModule时使用AlertModule.forRoot()?

[英]Why do I have to use AlertModule.forRoot() in imports of an NgModule?

我使用AlertModuleng2-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供应商部分。 这意味着如果你仅导入AlertModuleproviders不提供。 但是,当你调用forRoot它,它返回AlertModule除了与供应商AlertConfig

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM