【问题标题】:Why i get a "Nest can't resolve dependencies"为什么我得到“Nest 无法解决依赖关系”
【发布时间】:2023-03-31 14:22:01
【问题描述】:

我正在尝试找出为什么会出现以下错误:

Nest 无法解析 UniqueInteractionsService (?) 的依赖关系。 请确保索引 [0] 处的参数依赖项是 在 SharedModule 上下文中可用。

我的课程:

sharedModule.ts:

import {Module, Global} from '@nestjs/common';
import {InteractionsService} from "./elasticsearch/interactionsService";
import {UniqueInteractionsService} from "./elasticsearch/uniqueInteractionsService";
import {EsProvider} from "./elasticsearch/esProvider";

@Global()
@Module({
    exports: [InteractionsService, UniqueInteractionsService],
    providers: [EsProvider, InteractionsService, UniqueInteractionsService]
})
export class SharedModule {
}

interacionsService.ts:

import {ESService} from "./ESService";
import {Injectable, Inject} from '@nestjs/common';

@Injectable()
export class InteractionsService{

    constructor(@Inject(ESService) private readonly esService: ESService) {}

    // more stuff
}

uniqueInteractionsService.ts:

import {ESService} from "./ESService";
import {Injectable, Inject} from '@nestjs/common';

@Injectable()
export class UniqueInteractionsService{
    constructor(@Inject(ESService) private readonly esService: ESService) {}

    // more stuff
}

esProvider.ts:

import {ESService} from "./esService";

export const EsProvider = {
    provide: ESService,
    useFactory: async () => {
        const esService = new ESService();
        await esService.init();
        return esService;
    }
};

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    您正在从 SharedModule 导出 UniqueInteractionsService。在目标模块中,需要导入这个SharedModule,然后才能通过依赖注入在TargetModule所属的targetService中使用UniqueInteractionsService。

    例子:

    target-module.ts:
    @Module({
      imports: [SharedModule]
    })
    export class TargetModule {}
    

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 2020-05-31
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2022-01-17
      • 2018-11-21
      • 2020-03-12
      • 2020-07-03
      相关资源
      最近更新 更多