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