dav*_*avi 7 configuration node.js typescript nestjs
我有一个与任何嵌套模块都不相关的类。我想在此类中导入并使用我的 ConfigService。我可以在不将此类添加到任何模块的情况下执行此操作吗?或者我是否需要一个模块才能使用嵌套生成的类?
谢谢
小智 9
您可以像下面这样在课堂上创建
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);
}
}
Run Code Online (Sandbox Code Playgroud)
将此类添加为根模块中的提供者AppModule,
...
providers: [AppConfig],
...
Run Code Online (Sandbox Code Playgroud)
现在,一旦应用程序启动,您就可以在应用程序内的任何位置使用它,
AppConfig.get('database.port');
Run Code Online (Sandbox Code Playgroud)
希望这有帮助!
是的,您可以使用方法从 Nest.js DI 容器中获取任何内容app.get。
例如
const configService = app.get(ConfigService)
| 归档时间: |
|
| 查看次数: |
5191 次 |
| 最近记录: |