2

I wanted to implement the ConfigService of Nestjs v8.1.1

I've place the .env file in the project's root (not src folder) and the file has this content:

HOST=http://localhost
PORT=8088

The app.Module.ts is enriched with the import:

@Module({
  imports: [ 
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: '.env',
    }), 
   ...]

I've tried without the options and with these listed options.

When it is trying to get the value of the variable, it results in

var address = this.configService.get('HOST', 'http://localhost')
                                     ^
TypeError: Cannot read properties of undefined (reading 'get')

FYI the code is run in an extended class, which should not make a difference.

export default class KsqldbSignalsClient extends ClientProxy {

  constructor(private configService: ConfigService) {
    super()
  }
    
  async connect(): Promise<any> {
    var address = this.configService.get('HOST', 'http://localhost')
    ...

Any hint (even confirmation that it works for you) is appreciated.

feder
  • 1,849
  • 2
  • 25
  • 43

2 Answers2

1

Decorate the KsqldbSignalsClient class with @Injectable().

msrumon
  • 1,250
  • 1
  • 10
  • 27
0

Step 1: Install the 2 packages below

https://www.npmjs.com/package/config

https://www.npmjs.com/package/dotenv

Step 2:

@Module({
  imports: [ 
    ConfigModule.forRoot({
      host: process.env.HOST,
      port: process.env.PORT,
      envFilePath: '.env',
    }), 
   ...]

Step 3:

Then inside you KsqldbSignalsClient class or anywhere simply get the value like,

var address = process.env.HOST;
Musabbir Mamun
  • 251
  • 3
  • 6
  • 1
    The idea of config service is to access all env variables via the config service instead of a direct approach. – Avi Siboni Jan 18 '22 at 09:58