I want to create configurable Angular 9 module with IVY and AOT on.
IVY and AOT on by default in current version of Angular:
npx @angular/cli@9.0.6 new ng-modules --style=scss --routing=false
In the simplest scenario it must provide a single stateful service configurable by name:
counter.module.ts
@Injectable()
export class CounterService {
private counter = 0;
shot() {
return this.counter++;
}
}
@NgModule()
export class CounterModule {
static withConfig(name: string): ModuleWithProviders {
return {
ngModule: CounterModule,
providers: [{
provide: name,
useClass: CounterService
}]
};
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CounterModule.withConfig('main.CountService'),
CounterModule.withConfig('integration.CountService'),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'ng-modules-shots';
constructor(
@Inject('main.CountService') counter: CounterService,
) {
this.title = '' + counter.shot();
}
}
Everything works fine at this point. But if I want to add any logic into CounterModule.withConfig :
counter.module.ts
...
@NgModule()
export class CounterModule {
static withConfig(name?: string): ModuleWithProviders {
const counterProviderToken = name ? name : CounterService;
return {
ngModule: CounterModule,
providers: [{
provide: counterProviderToken,
useClass: CounterService
}]
};
}
}
I'm getting an error:
ERROR in src/app/app.module.ts:11:16 - error NG1010: Value at position 1 in the NgModule.imports of AppModule is not a reference: [object Object]
What can I do about it? Fix it somehow? Maybe there is another approach to make configurable modules?