首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我必须在导入AlertModule.forRoot()时使用NgModule ()?

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

Stack Overflow用户
提问于 2017-09-17 09:46:06
回答 1查看 1.5K关注 0票数 5

我使用的是来自AlertModuleng2-bootstrap。在imports部分,如果我只使用AlertModule,就会得到错误Value: Error: No provider for AlertConfig!。如果我使用AlertModule.forRoot(),应用程序可以正常工作。为什么?

我的app.module.ts

代码语言:javascript
复制
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 { }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-17 09:48:49

forRoot命名为静态函数有它们的自己的目的。它们用于应用程序级别的单例服务。

AlertModule中没有任何提供程序。当您调用forRoot时,它返回一个类型为ModuleWithProviders的对象,其中包括带有声明的AlertModule本身以及在AlertModule中使用的提供程序。

这就是在AlertModule - github源中所写的

代码语言:javascript
复制
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加法。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46262678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档