Nestjs依赖注入-将服务注入服务

时间:2020-05-22 10:42:31

标签: typescript dependency-injection 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.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() {}
}

1 个答案:

答案 0 :(得分:1)

根据您的错误,您在某个地方的AService数组中有imports,这不是您在NestJS中所做的。分解

错误:Nest无法解析AService的依赖项(?)。

请确保AService上下文中的索引为[0]的BService参数可用。

第一部分显示了提供者遇到的困难,以及未知依赖项所在的?。在这种情况下,AService是无法实例化的提供者,而BService是未知依赖项。

错误的第二部分是显式地调用注入令牌(通常是类名)和构造函数中的索引,然后是在Nest正在查看的 module 上下文中。您可以阅读Nest所说的

AService上下文中

意思是Nest正在查看名为AService的模块。正如我之前所说,这是您不应该做的事情。

如果在另一个模块中需要AService,则应将AService添加到AModule的{​​{1}}数组中,并向其中添加exports新模块的AModule数组。