繁体   English   中英

导入后如何使用全局模块?

[英]How to use global module after imported?

我已经按照文档中的示例创建了基本的配置服务。

在本教程的底部,您可以选择全局声明:

“您可以将ConfigModule声明为全局模块,而不是在所有模块中重复导入ConfigModule 。”

因此,遵循以下有关全局模块的文档:

  • @nestjs/commonGlobal导入ConfigModule
  • ConfigModule添加了@Global()装饰器。
  • ConfigModule导入AppModule
  • imports数组添加了ConfigModule

下一个是什么? 我试图将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并从任何模块访问它。

您在AppService缺少this限定符:

getHello(): string {
  return this.config.get('DB_NAME');
         ^^^^^
}

此外,导入丢失:

import { ConfigService } from './config/config.service';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM