gpt4 book ai didi

javascript - Nest 无法解析 RestController 的依赖关系

转载 作者:行者123 更新时间:2023-12-01 00:26:58 25 4
gpt4 key购买 nike

我正在一个新的 Nest.js 项目中工作,每当我尝试启动服务器时:

[ExceptionHandler] Nest can't resolve dependencies of the RestController (?). Please make sure that the argument dependency at index [0] is available in the RestModule context.

我检查了文档并到处查看,但找不到问题所在。 RestController 类注入(inject) UsersService,它由 UsersModule 导出并在 RestModule 中导入。一切看起来都很好,但没有成功。

这是我的代码:

app.module.ts:

import { Module } from '@nestjs/common'
import { RestModule } from './rest/rest.module'

@Module({
imports: [
RestModule
]
})
export class AppModule { }

rest.module.ts:

import { Module } from '@nestjs/common'
import { RestController } from './rest.controller'
import { UsersModule } from '../users/users.module'

@Module({
imports: [
UsersModule
],
controllers: [
RestController
]
})
export class RestModule { }

rest.controller.ts:

import { Controller, Inject, Get } from '@nestjs/common'
import { UsersService } from '../users/users.service'
import { User } from '../users/user.interface'

@Controller()
export class RestController {

constructor (
@Inject()
private readonly usersService: UsersService
) { }

@Get()
async getAll (): Promise<User[]> {
return this.usersService.findAll()
}

}

users.module.ts:

import { Module } from '@nestjs/common'
import { UsersService } from './users.service'

@Module({
providers: [
UsersService
],
exports: [
UsersService
]
})
export class UsersModule { }

users.service.ts:

import { Injectable } from '@nestjs/common'
import { User } from './user.interface'

@Injectable()
export class UsersService {

async findAll (): Promise<User[]> {
return new Promise((resolve, reject) => resolve([]))
}

}

提前谢谢您!

最佳答案

在您的 RestController 类中,您必须从构造函数中删除 @Inject():

constructor (
private readonly usersService: UsersService
) { }

@Inject() 可用于 non-class-based provider tokens .

关于javascript - Nest 无法解析 RestController 的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895734/

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