我在包依赖项中有一个包含提供程序的模块。但是当我尝试在我的app.module中使用它时,我得到:
Error: No provider for EnvService!
/node_modules/common-components/env.module:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WindowService } from './window.service';
import { EnvService } from './env.service';
export function windowFactory() {
return window;
}
@NgModule({
imports: [
CommonModule
]
})
export class EnvModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: EnvModule,
providers: [
EnvService,
{ provide: WindowService, useFactory: windowFactory }
]
}
}
}
app.module.ts
import { EnvModule } from 'common-components';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
EnvModule.forRoot()
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
答案 0 :(得分:0)
同时在模块的提供者中包含EnvService
:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WindowService } from './window.service';
import { EnvService } from './env.service';
export function windowFactory() {
return window;
}
@NgModule({
imports: [
CommonModule
],
providers: [
EnvService
]
})
export class EnvModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: EnvModule,
providers: [
EnvService,
{ provide: WindowService, useFactory: windowFactory }
]
}
}
}