typescript 从另一个模块注入 nestjs 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51819504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject nestjs service from another module
提问by Fairydhwen
I've got a PlayersModule
and an ItemsModule
.
我有一个PlayersModule
和一个ItemsModule
。
I want to use the ItemsService
in the PlayersService
.
我想ItemsService
在PlayersService
.
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){}
I get this nest error :
我收到此嵌套错误:
[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.
[Nest] 11592 - 2018-8-13 11:42:17 [ExceptionHandler] Nest 无法解析 PlayersService (+, ?) 的依赖关系。请确保索引 [1] 处的参数在当前上下文中可用。
Both modules are imported in the app.module.ts
. Both services are working alone in their module.
这两个模块都导入到app.module.ts
. 这两个服务都在它们的模块中单独工作。
回答by Kim Kern
You have to exportthe ItemsService
in the module that provides it:
你要导出的ItemsService
是它提供的模块:
@Module({
controllers: [ItemsController],
providers: [ItemsService],
exports: [ItemsService]
^^^^^^^^^^^^^^^^^^^^^^^
})
export class ItemsModule {}
and then import the exporting modulein the module that uses the service:
然后在使用该服务的模块中导入导出模块:
@Module({
controllers: [PlayersController],
providers: [PlayersService],
imports: [ItemsModule]
^^^^^^^^^^^^^^^^^^^^^^
})
export class PlayersModule {}
回答by Eyal Israel
I believe that you faced the same problem i had. My scenario was 2 sibling custom modules (user, auth) that needed to use each other's services. I used circular DIto solve it. please check this link
我相信你遇到了和我一样的问题。我的场景是需要使用彼此服务的 2 个兄弟自定义模块(用户、身份验证)。我使用循环 DI来解决它。请检查此链接
Let me know whether if it solved your issue, maybe I can advise you further.
让我知道它是否解决了您的问题,也许我可以为您提供进一步的建议。
回答by Ben Stickley
I solved this problem my removing @Inject()
from the argument in my constructor that was passing the exported service.
我解决了这个问题,我@Inject()
从传递导出服务的构造函数中删除了参数。