具有依赖关系的AOT NgModule提供程序,NullInjectorError

时间:2018-06-15 18:37:12

标签: angular typescript ionic2 angular2-aot

我已经尝试了https://stackoverflow.com/a/43293449/513570中的实施:

@NgModule()
export class SampleModule {
  static forRoot(config: CustomConfig): ModuleWithProviders {
    // User config get logged here
    console.log(config);
    return {
      ngModule: SampleModule,
      providers: [SampleService, {provide: 'config', useValue: config}]
    };
  }
}
@Injectable()
export class SampleService {

  constructor(@Inject('config') private config:CustomConfig) {
const sConfig = {
    key: 'value'
};


@NgModule({
    declarations: [
        ...
    ],
    imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp),
        IonicStorageModule.forRoot(),
        SampleModule.forRoot(sConfig),
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        ...
    ],
    providers: [
        ...,
        // { provide: SampleService, useFactory: () => new SampleService(sConfig) 
    ],
})
export class AppModule { }

如果服务是在providers(注释代码)而不是imports中导入的,那么在开发和AOT中一切正常。

但是给定的代码只有代码在开发模式下工作正常。在AOT中它引发了以下错误:

StaticInjectorError[l]: 
  StaticInjectorError[l]: 
    NullInjectorError: No provider for l!

我一直在使用live-reload服务并在编译应用程序时保留登录chrome,并且在某些时候(在我猜错之前)错误是:

StaticInjectorError[SampleService]: 
  StaticInjectorError[SampleService]: 
    NullInjectorError: No provider for SampleService!

我也试图提供export const SampleServiceToken = new InjectionToken<string>('SampleService');

它的唯一工作方式是在主应用程序@NgModule中提供服务:

@NgModule({
    ...
    providers: [
        { provide: SampleService, useFactory: () => new SampleService(config) },
    ],
})

依赖关系:

"@angular/common": "5.0.3",
"@angular/compiler": "5.0.3",
"@angular/compiler-cli": "5.0.3",
"@angular/core": "5.0.3",
"@angular/forms": "5.0.3",
"@angular/http": "5.0.3",
"@angular/platform-browser": "5.0.3",
"@angular/platform-browser-dynamic": "5.0.3",
"@ionic-native/core": "^4.4.0",
"@ionic-native/splash-screen": "4.4.0",
"@ionic-native/status-bar": "4.4.0",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",

0 个答案:

没有答案