Configurable angular 9 module

Viewed 688

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?

1 Answers

There's currently a constraint that there's only a single statement in the function. So if you want to add any logic to it and keep AOT work, it should be placed inside this statement.

...
@NgModule()
export class CounterModule {
  static withConfig(name?: string): ModuleWithProviders {
    return {
      ngModule: CounterModule,
      providers: [{
        provide: name ? name : CounterService,
        useClass: CounterService
      }]
    };
  }
}

You can use a function to generate providers in this module, though:

...
@NgModule()
export class CounterModule {
  static withConfig(name?: string): ModuleWithProviders {
    return {
      ngModule: CounterModule,
      providers: this.generateProviders(name)
    };
  }

  private static generateProviders(name?: string): Provider[] {
    const counterProviderToken = name ? name : CounterService;
    return [{
      provide: counterProviderToken,
      useClass: CounterService
    }]
  }
}
Related