gpt4 book ai didi

nestjs - 如何在 NestJS 中跨模块全局注入(inject)值(value)?

转载 作者:行者123 更新时间:2023-12-02 05:14:18 25 4
gpt4 key购买 nike

我正在使用 nx 工作区和 Nestjs。我想在 Nestjs 应用程序的多个模块中注入(inject)一个值。

最终目标是重现与 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它需要访问此全局注入(inject)值?

这在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 {}

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

关于nestjs - 如何在 NestJS 中跨模块全局注入(inject)值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com