【问题标题】:How to use global module after imported?导入后如何使用全局模块?
【发布时间】:2019-06-27 21:51:23
【问题描述】:

我已经按照docs 中的示例介绍了如何创建基本配置服务。

在教程的底部它说你可以选择全局声明它:

“除了在所有模块中重复导入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 并从任何模块访问它。

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案1】:

    您的AppService 中缺少this 限定符:

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

    另外,缺少导入:

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

    【讨论】:

    • 表示不需要多次导入(注册)ConfigModule;在AppModule 中只有一次。但是,ConfigService 必须在任何使用它的地方导入(注入)。
    • 这更有意义,谢谢。最后一点的措辞让我感到困惑。 “之后,CatsService 提供者将无处不在,尽管 CatsModule 不会被导入。”只有提供者无处不在。谢谢。
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 2021-11-16
    • 2021-02-26
    • 2021-12-14
    • 2010-11-05
    • 2020-04-23
    • 2019-02-26
    相关资源
    最近更新 更多