Fuz*_*per 13 dependency-injection typescript 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.
Run Code Online (Sandbox Code Playgroud)
我找不到任何方法来相互注入服务。这是否不受支持,有点反模式......?
如果是这样,如何处理具有我希望在多个组件和服务中的所有应用程序中可用的功能的服务?
代码如下:
b.模块.ts
import { Module } from '@nestjs/common';
import { BService } from './b.service';
@Module({
imports: [],
exports: [bService],
providers: [bService]
})
export class bModule { }
Run Code Online (Sandbox Code Playgroud)
b.服务.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class BService {
someFunc();
}
Run Code Online (Sandbox Code Playgroud)
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 {
}
Run Code Online (Sandbox Code Playgroud)
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() {}
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*iel 14
根据您的错误,您在某个地方有AService一个imports数组,这不是您在 NestJS 中执行的操作。把它分解
错误:Nest 无法解析 AService 的依赖关系(?)。
请确保索引 [0] 处的参数 BService 在 AService 上下文中可用。
第一部分显示遇到困难的提供者以及?未知依赖项所在的位置。在本例中,AService是无法实例化的提供者,并且BService是未知的依赖项。
错误的第二部分是显式调用构造函数中的注入标记(通常是类名)和索引,然后调用Nest 正在查看的模块上下文。你可以读到 Nest 说的
AService在上下文中
意思是 Nest 正在查看一个名为 的模块AService。正如我之前所说,这是你不应该做的事情。
如果您在另一个模块中需要AService,则应该将 添加到的数组AService中,然后添加到新模块的数组中。AModuleexportsAModuleimports
| 归档时间: |
|
| 查看次数: |
17437 次 |
| 最近记录: |