Why should I use AlertModule.forRoot () in an NgModule import?

I use AlertModulefrom ng2-bootstrap. In the section imports, if I just use AlertModule, I get an error Value: Error: No provider for AlertConfig!. If I use AlertModule.forRoot(), the application works fine. Why?

My 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 { }
+4
source share
1 answer

forRootThe named static functions have their own goals . They are used for peer-to-peer application-level services.

AlertModulethere are no suppliers in it. When you call forRoot, it returns an object of type ModuleWithProviders , which includes with its declarations and providers that are used in . AlertModuleAlertModule

, 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.

+3

Source: https://habr.com/ru/post/1685820/


All Articles