我按照 docs 中的示例进行操作关于如何创建基本配置服务。
在教程的底部,它说您可以选择全局声明它:
“您还可以将 ConfigModule
声明为全局模块,而不是在所有模块中重复导入 ConfigModule
。”
因此,按照我的全局模块文档:
- 将
Global
从@nestjs/common
导入到ConfigModule
中。 - 向
ConfigModule
添加了@Global()
装饰器。 - 将
ConfigModule
导入到AppModule
中。 - 将
ConfigModule
添加到imports
数组中。
那么下一步是什么?我尝试将 ConfigService
注入(inject) AppService
但它无法解析。
app.module.ts:
import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { AppController } from './app.controller';
import { ConfigModule } from '../config/config.module';
@Module({
imports: [
ConfigModule,
],
controllers: [
AppController,
],
providers: [
AppService,
],
})
export class AppModule {}
app.service.ts:
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
private readonly config: ConfigService;
constructor(config: ConfigService) {
this.config = config;
}
getHello(): string {
return config.get('DB_NAME');
}
}
config.module.ts:
import { Module, Global } from '@nestjs/common';
import { ConfigService } from './config.service';
@Global()
@Module({
providers: [
{
provide: ConfigService,
useValue: new ConfigService(`${process.env.NODE_ENV}.env`),
},
],
exports: [
ConfigService,
],
})
export class ConfigModule {}
config.service.ts:
import * as dotenv from 'dotenv';
import * as fs from 'fs';
export class ConfigService {
private readonly envConfig: { [key: string]: string };
constructor(filePath: string) {
this.envConfig = dotenv.parse(fs.readFileSync(filePath));
}
get(key: string): string {
return this.envConfig[key];
}
}
我希望能够注入(inject) ConfigService
并从任何模块访问它。
最佳答案
您在 AppService
中缺少 this
限定符:
getHello(): string {
return this.config.get('DB_NAME');
^^^^^
}
此外,导入丢失:
import { ConfigService } from './config/config.service';
关于javascript - 导入后如何使用全局模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511348/