如何在 NestJS 中跨模块全局注入价值?

How to globally inject value across modules in NestJS?

我正在使用 nx workspace 和 nestjs。 我想在 nestjs 应用程序中跨多个模块注入一个值。

最终目标是重现与 vsavkin mentioned for Angular

类似的配置管理方式

不过好像不行,或者我漏掉了什么。

Nest can't resolve dependencies of the FeatureService (?). Please make sure that the argument at index [0] is available in the FeatureModule context.

如何通知 FeatureModule 它需要访问这个全局注入值?

这在 AppService(根模块中的服务)中工作正常,但在任何子模块中都没有。

下面是我的代码。 或者 codesandbox.io

上的完整示例

app.module.ts

@Module({
  imports: [
    FeatureModule
  ],
  controllers: [
    AppController
  ],
  providers: [
    AppService,
    {
      provide: 'MY-TOKEN',
      useValue: 'my-injected-value',
    }
  ],
})
export class AppModule {}

feature.module.ts

@Module({
  imports: [],
  controllers: [],
  providers: [
    FeatureService
  ],
})
export class FeatureModule {
}

feature.service.ts

@Injectable()
export class AppService {
  constructor(
    @Inject('MY-TOKEN') private injectedValue: string
  ) {}
}

引自 NestJS official documentation:

In Angular, the providers are registered in the global scope. Once defined, they're available everywhere. On the other hand, Nest encapsulates providers inside the module scope. You aren't able to use the module providers elsewhere without importing them. But sometimes, you may just want to provide a set of things which should be available always - out-of-the-box, for example: helpers, database connection, whatever. That's why you're able to make the module a global one.

所以你可以做的就是用 MY-TOKEN 提供商定义一个全局模块:


@Global()
@Module({  
  providers: [
    {
      provide: 'MY-TOKEN',
      useValue: 'my-injected-value',
    }
  ],
  exports: ['MY-TOKEN'],
})
export class GlobalModule {}

然后您可以使用它导出的值,而无需在任何地方导入全局模块。