首页 > 解决方案 > 如何在 NestJS 中将全局提供程序导入另一个全局提供程序?

问题描述

我想将文档中的配置提供程序导入另一个提供程序。

我正在使用此处文档中播种的相同配置结构。

所以config.module.ts看起来像这样:

import { Module, Global } from '@nestjs/common';
import { ConfigService } from './config.service';

@Global()
@Module({
  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(
        `config/env/${process.env.NODE_ENV || 'development'}.env`,
      ),
    },
  ],
  exports: [ConfigService],
})
export class ConfigModule {}

另一个提供者应该看起来像这样正确吗?

token.module.ts

import { Module, Global } from '@nestjs/common';
import { TokenService} from './token.service';
import { ConfigService } from './config.service';

@Global()
@Module({
  import: [ConfigService]
  providers: [TokenService],
  exports: [TokenService],
})
export class TokenModule {}

虽然 TokenService 应该看起来像这样

token.service.ts

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

export class TokenService {
  constructor(private readonly configService: ConfigService) {}

  test(): string {
    return this.configService.get('TestVal');
  }
}

但是当我在 AppModule 中导入 TokenModule 时出现此错误The "path" argument must be one of type string, Buffer, or URL. Received type undefined

标签: nestjs

解决方案


您忘记将您的标记TokenService@Injectable(). 你需要告诉 NestJS 需要提供给其他服务的参数。


推荐阅读