gpt4 book ai didi

nestjs - 如何将服务注入(inject)到导入的服务 Nestjs

转载 作者:行者123 更新时间:2023-12-04 04:28:34 24 4
gpt4 key购买 nike

我有自定义模块 AuthModuleAuthService , AuthController使用路线等,工作正常,并希望在几个项目之间共享这个模块作为一个包。问题是如何扩展导入的AuthService从此包中以及如何在其中注入(inject)其他服务?

更多详情

进入我的定制AuthService ,我想放在包中,是注入(inject)类 UserService ,默认情况下从数据库中获取一些 User数据并将其返回给客户端。我需要注入(inject) AuthService另一个,例如 ProfileService来自应用程序,从数据库中获取 User额外的数据。目的是合并User主要数据和User额外的数据,并将这束返回给客户端

最佳答案

我认为这里不需要动态模块。

实际上,只需要从您的 AuthModule 中导出您想要注入(inject)到由 NestJs 管理的其他实体的服务,并在您希望其他实体注入(inject)您的 AuthService 的模块中导入 AuthModule。

import { Module } from '@nestjs/common'
import { AuthService } from './AuthService'

@Module({
providers: [
AuthService,
// ... others
],
exports: [
AuthService
]
})
export class CommonModule {}


然后在您的依赖类(假设是另一个 Controller ,但可以是 GraphQL 解析器、拦截器或其他任何东西)中,您声明对 AuthService 的依赖。

import { AuthService } from '../auth/AuthService'
import { Dependencies } from '@nestjs/common'

@Dependencies(AuthService)
export class DependentController {
constructor (authService) {
this.authService = authService
}
}

最后,为了 AuthService 对依赖的 Controller 可用,它必须被导入到提供 Controller 的同一个模块中。

import { Module } from '@nestjs/common'
import { CommonModule } from '../auth/CommonModule'
import { DependentController } from './controller/DependentController'

@Module({
imports: [
CommonModule,
// ...others
],
providers: [
DependentController,
// ...others
]
})
export class ControllerModule {}

我知道语法可以更短,并且在 typescript 中不使用依赖装饰器,但是问题的核心是从它提供的模块中导出共享服务,然后将该模块导入到模块中其他需要它的类中。

关于nestjs - 如何将服务注入(inject)到导入的服务 Nestjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com