- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我是一名优秀的程序员,十分优秀!