[英]Nestjs Dependency Injection - Inject service into service
我有一项服务,可以毫无问题地注入其他组件。
当我尝试将该服务注入另一个服务时,我得到
Error: Nest can't resolve dependencies of the AService (?).
Please make sure that the argument BService at index [0] is available in the AService context.
我找不到任何方法将服务相互注入。 这是不支持的,一种反模式....?
如果是这样,如何处理具有我希望在我的所有应用程序中的多个组件和服务中可用的功能的服务?
代码如下:
b.module.ts
import { Module } from '@nestjs/common';
import { BService } from './b.service';
@Module({
imports: [],
exports: [bService],
providers: [bService]
})
export class bModule { }
b.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class BService {
someFunc();
}
a.module.ts
import { Module } from '@nestjs/common';
import { SensorsService } from './a.service';
import { SensorsController } from './a.controller';
import { BModule } from '../shared/b.module';
@Module({
imports: [BModule],
providers: [AService],
controllers: [AController],
exports: []
})
export class AModule {
}
a.service.ts - 应该可以使用 b.service
import { Injectable } from '@nestjs/common';
import { BService } from '../shared/b.service';
@Injectable()
export class AService {
constructor(
private bService: BService
) {}
someOtherFunc() {}
}
根据您的错误,您在某处的imports
数组中有AService
,这不是您在 NestJS 中所做的事情。 把它分解
错误:Nest 无法解析 AService (?) 的依赖关系。
请确保索引 [0] 处的参数 BService 在 AService 上下文中可用。
第一部分显示有困难的提供者,以及一个?
未知依赖项在哪里。 在这种情况下, AService
是无法实例化的提供者,而BService
是未知依赖项。
错误的第二部分是显式调用注入令牌(通常是 class 名称)和构造函数中的索引,然后是 Nest 正在查看的模块上下文。 你可以读到 Nest 说
在
AService
上下文中
这意味着 Nest 正在查看一个名为AService
的模块。 正如我之前所说,这是你不应该做的事情。
如果您在另一个模块中需要AService
,则应将AService
添加到AModule
的exports
数组中,并将AModule
添加到新模块的imports
数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.