从另一个模块注入 nestjs 服务 [英] Inject nestjs service from another module

查看:36
本文介绍了从另一个模块注入 nestjs 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PlayersModule 和一个 ItemsModule.

I've got a PlayersModule and an ItemsModule.

我想使用 PlayersService 中的 ItemsService.

当我通过注入添加它时:

When I add it by injection:

import { Injectable } from '@nestjs/common';
import { InjectModel } from 'nestjs-typegoose';
import { ModelType, Ref } from 'typegoose';
import { Player } from './player.model';
import { Item } from '../items/item.model';
import { ItemsService } from '../items/items.service';

@Injectable()
export class PlayersService {
    constructor(
        @InjectModel(Player) private readonly playerModel: ModelType<Player>,
        private readonly itemsService: ItemsService){}

我收到此嵌套错误:

[Nest] 11592 - 2018-8-13 11:42:17 [ExceptionHandler] Nest 不能解决 PlayersService 的依赖关系(+,?).请确保索引 [1] 处的参数在当前上下文中可用.

[Nest] 11592 - 2018-8-13 11:42:17 [ExceptionHandler] Nest can't resolve dependencies of the PlayersService (+, ?). Please make sure that the argument at index [1] is available in the current context.

两个模块都导入到 app.module.ts 中.这两个服务在各自的模块中单独运行.

Both modules are imported in the app.module.ts. Both services are working alone in their module.

推荐答案

你必须在提供它的模块中导出ItemsService:

You have to export the ItemsService in the module that provides it:

@Module({
  controllers: [ItemsController],
  providers: [ItemsService],
  exports: [ItemsService]
  ^^^^^^^^^^^^^^^^^^^^^^^
})
export class ItemsModule {}

然后在使用该服务的模块中导入导出的模块:

and then import the exporting module in the module that uses the service:

@Module({
  controllers: [PlayersController],
  providers: [PlayersService],
  imports: [ItemsModule]
  ^^^^^^^^^^^^^^^^^^^^^^
})
export class PlayersModule {}

⚠️ 不要将同一个提供者添加到多个模块中.导出提供者,导入模块.⚠️

⚠️ Do not add the same provider to multiple modules. Export the provider, import the module. ⚠️

这篇关于从另一个模块注入 nestjs 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆