I am interested in developing a customizable Angular 9 module with IVY and AOT enabled.
In the latest version of Angular, IVY and AOT are automatically activated:
npx @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8e8184add4c3ddc3db">[email protected]</a> new ng-modules --style=scss --routing=false
The goal is to create a single stateful service within the module that can be configured by its name:
counter.module.ts
@Injectable()
export class CounterService {
private counter = 0;
shoot() {
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.shoot();
}
}
Everything behaves as expected at this point. However, when attempting to modify CounterModule.withConfig
, I encounter an issue:
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
}]
};
}
}
An error message appears:
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 steps should be taken to resolve this issue? Is there an alternative method for creating configurable modules?