【问题标题】:Nestjs Dependency Injection - Inject service into serviceNestjs 依赖注入 - 将服务注入服务
【发布时间】:2020-09-09 04:26:56
【问题描述】:

我有一项服务可以毫无问题地注入其他组件。

当我尝试将该服务注入另一个服务时,我得到了

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() {}
}

【问题讨论】:

  • 我注意到您在声明代码中的模块是bModule,但是您正在导入BModule - 这是问题所在吗?与bService 相同
  • JavaScript 区分大小写。确保您有适合您的类和实例的案例。另外,如果不是这样,您会展示这些如何绑定到您的AppModule 吗?
  • @hlfrmn 我的模块当然还有其他名称。但是由于它在遍历代码后突然开始工作,我会认为它是这样的失败。

标签: typescript dependency-injection nestjs


【解决方案1】:

根据您的错误,您在某处的 imports 数组中有 AService,这不是您在 NestJS 中所做的事情。分解它

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

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

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

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

AService 上下文中

意思是 Nest 正在研究一个名为 AService 的模块。正如我之前所说,这是你不应该做的事情。

如果您在另一个模块中需要AService,则应将AService 添加到AModuleexports 数组中,并将AModule 添加到新模块的imports 数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多