我已经按照文档中的示例创建了基本的配置服务。
在本教程的底部,您可以选择全局声明:
“除了ConfigModule
在所有模块中重复导入之外,您还可以声明ConfigModule
为全局模块。”
因此,遵循以下有关全局模块的文档:
Global
自@nestjs/common
成ConfigModule
。@Global()
装饰器添加到ConfigModule
。ConfigModule
到AppModule
。ConfigModule
到imports
数组。下一个是什么?我曾尝试以注入ConfigService
到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];
}
}
我希望能够ConfigService
从任何模块中注入和访问它。
您缺少您中的this
限定词AppService
:
getHello(): string {
return this.config.get('DB_NAME');
^^^^^
}
另外,导入丢失:
import { ConfigService } from './config/config.service';
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句