Search code examples
angulardependency-injectionangular-module

Angular import module and pass it's config with service injection


In nestjs framework (which is highly inspired by Angular), when I want to pass some setting (from env file) when importing a module, I do the following:

// nestjs
@Module({
  imports: [
    // usually modules has registerAsync method
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET'),
      }),
      inject: [ConfigService],
    }),
  ]
})
export class AuthModule {}

I actually use dependency injection in useFactory. How is this possible in Angular?


Solution

  • This @Module looks exaclty the same as @NgModule, so its the same.

    https://angular.io/guide/dependency-injection-providers#using-factory-providers

    If you need to dynamically configure module that is imported, it is possible using ModuleWithProviders. This is exactly what RouterModule.forRoot does

    https://angular.io/api/router/RouterModule#routermodule