0

I have a Module with Providers in a package dependency. But when I try to use it in my app.module I get:

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 { }
BSMP
  • 4,596
  • 8
  • 33
  • 44
Marcio M.
  • 371
  • 1
  • 6
  • 15

1 Answers1

0

Include the EnvService in the providers of the module as well:

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 }
      ]
    }
  }
}
0mpurdy
  • 3,198
  • 1
  • 19
  • 28