I'm working in a new Nest.js project and whenever I try to start the server:
[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.
I've checked the documentation and looked everywhere and i cannot spot the problem. The RestController
class injects UsersService
, which is exported by UsersModule
and imported in RestModule
. Everything looks fine but didn't work.
This is my code:
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([]))
}
}
Thank you in advance!
In your RestController
class you have to remove the @Inject()
from your constructor:
constructor (
private readonly usersService: UsersService
) { }
@Inject()
can be used for non-class-based provider tokens .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.