Nestjs依赖注入-将服务注入服务 [英] Nestjs Dependency Injection - Inject service into service
本文介绍了Nestjs依赖注入-将服务注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个服务,我可以将其插入到其他组件中,而不会出现任何问题。
当我尝试将该服务注入另一个服务时,收到
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.mode.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 e.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中要做的事情。要分解它
第一部分显示遇到困难的提供程序,以及未知依赖项所在的错误:嵌套无法解析aService(?)的依赖项。
请确保索引[0]处的参数BService在aService上下文中可用。
?
。在这种情况下,AService
是无法实例化的提供程序,BService
是未知依赖项。
错误的第二部分是显式调用构造函数中的注入令牌(通常是类名)和索引,然后在模块上下文Nest查看的内容中调用。你可以看到Nest说
在
AService
上下文中
表示Nest正在查看名为AService
的模块。正如我之前所说的,这是您不应该做的事情。
如果您需要其他模块中的AService
,则应将AService
添加到AModule
的exports
数组中,并将AModule
添加到新模块的imports
数组中。
这篇关于Nestjs依赖注入-将服务注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文