簡體   English   中英

Nestjs 依賴注入 - 將服務注入服務

[英]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添加到AModuleexports數組中,並將AModule添加到新模塊的imports數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM