简体   繁体   中英

How to use global module after imported?

I've followed the example from the docs on how to create a basic config service.

At the bottom of the tutorial it says you can opt to declare it globally:

"Instead of importing ConfigModule repeatingly in all your modules, you can also declare ConfigModule as a global module."

So following the documentation for global modules I have:

  • Imported Global from @nestjs/common into ConfigModule .
  • Added the @Global() decorator to ConfigModule .
  • Imported ConfigModule into AppModule .
  • Added ConfigModule to the imports array.

So what's next? I have tried to inject ConfigService into AppService however it doesn't resolve.

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];
  }
}

I expect to be able to inject ConfigService and access it from any module.

You're missing the this qualifier in your AppService :

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

Also, the import is missing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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