I have a class that is not related to any nest modules. I wanted to import and use my ConfigService inside of this class. Can I do this without adding this class to any module or do I need to have a module in order to use nest generated classes?
Thanks
CodePudding user response:
Yep, you can get anything from Nest.js DI container using app.get
method.
e.g.
const configService = app.get(ConfigService)
CodePudding user response:
You can create on class like below
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppConfig {
static service: ConfigService;
constructor(service: ConfigService) {
AppConfig.service = service;
}
static get(key: string): any {
return AppConfig.service.get(key);
}
}
add this class as a provider in your root module AppModule
,
...
providers: [AppConfig],
...
now once the app is booted, you can use it as following anywhere inside app,
AppConfig.get('database.port');
Hope this helped!