AOT NgModule provider with dependencies, NullInjectorError

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I've tried the implementation in 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 { } 

If the service is imported in providers (commented code) instead of imports, all works fine in development and AOT.

But the given code only code works fine in development mode. In AOT it raises the following error:

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

I've been serving with live-reload and preserve log in chrome while compiling the app and at some point (before mangling I suppose) the error is:

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

I've also tried to provide with export const SampleServiceToken = new InjectionToken<string>('SampleService');

The only way it works is to provide the service in the main app @NgModule:

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

dependencies:

"@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", 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!