nest: [ExceptionHandler] Nest can't resolve dependencies of the UserController (?, +)...

I’m submitting a…


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Trying to use my UserService.ts and AuthService.ts in my UserController.ts, but I get the following error: [ExceptionHandler] Nest can't resolve dependencies of the UserController (?, +). Please make sure that the argument at index [0] is available in the current context.

Minimal reproduction of the problem with instructions

application.module.ts

import { Module } from "@nestjs/common";
import { ApplicationController } from "controllers/application.controller";
import { ApplicationService } from "services/application.service";
import { AuthModule } from "./auth.module";
import { UserModule } from "./user.module";

@Module({
  imports: [
    AuthModule,
    UserModule,
  ],
  controllers: [
    ApplicationController,
  ],
  providers: [
    ApplicationService,
  ],
})
export class ApplicationModule {}

user.module.ts

import { Module } from "@nestjs/common";
import { UserController } from "controllers/user.controller";

@Module({
  controllers: [
    UserController,
  ],
})
export class UserModule {}

user.service.ts

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserEntity } from "entities/user.entity";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly repository: Repository<UserEntity>,
  ) {}

  async findAll(): Promise<UserEntity[]> {
    return await this.repository.find();
  }
}

auth.module.ts

import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt";
import { AuthService } from "services/auth.service";

@Module({
  imports: [
    JwtModule.register({
      secretOrPrivateKey: "key12345",
    }),
  ],
})
export class AuthModule {}

auth.service.ts

import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { TokenJwtInterface } from "interfaces/token-jwt.interface";

@Injectable()
export class AuthService {
  private tokenType;

  constructor(private readonly jwtService: JwtService) {
    this.tokenType = "bearer";
  }

  public generateTokenJwt(
    payload: object,
    expiresIn: number,
  ): TokenJwtInterface {
    const accessToken = this.jwtService.sign(payload);

    return {
      access_token: accessToken,
      token_type: this.tokenType,
      refresh_token: "",
      expires_in: expiresIn,
    };
  }
}

user.controller.ts

import {
  Get,
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
} from "@nestjs/common";
import { UserService } from "services/user.service";
import { UserEntity } from "entities/user.entity";
import * as bcrypt from "bcryptjs";
import { AuthService } from "services/auth.service";

@Controller("/users")
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService,
  ) {}

  @Get()
  async root(): Promise<UserEntity[]> {
    return await this.userService.findAll();
  }
...

What is the motivation / use case for changing the behavior?

Bugfix?

Environment


Nest version: 5.1.0

 
For Tooling issues:
- Node version: v8.11.3
- Platform:  Ubuntu

Others:
IDE: VSC

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 18 (4 by maintainers)

Most upvoted comments

AuthModule should provide AuthService, not ApplicationModule because AuthModule imports JwtModule, which exposes JwtService. If you imported JwtModule in ApplicationModule, it would work, but that wouldn’t be good separation of concerns

I’m interested in addressing any shortcomings in the documentation. What information was lacking/confusing (maybe you’ll know better after getting this resolved) ?

@johnbiundo I realize that this is not really the place to discuss this (i should open an issue) but since i was browsing this issue and you just asked, so here are two quick personal suggestions about the docs:

  • Search functionality
  • The linking inside the different articles of the docs to the relevant samples in this repo, i think that they are too ‘hidden’ and do not get their deserved stage exposition.

Important note: This post is only for those who has similar problem, but not exactly the same like reporter. Related to typing.

Previously (when error occurred), I had in users.controller.ts:

// Problematic nesting in services object:
constructor(private readonly services: { users: UsersService }) { }

What was helpful for me:

// Flat variable according to documentation:
constructor(private readonly userService: UsersService) { }

For those who might be interested, I ran into the same problem and was able to solve it by including TypeOrmModule.forFeature() in the imports section of auth.module.ts file.

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { UserService } from '../../user/user.service';
import { UserEntity } from '../../user/user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forFeature([UserEntity]),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secret',
      signOptions: { expiresIn: '30m' },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy, UserService],
})
export class AuthModule {}

Check https://docs.nestjs.com/techniques/database - you need to add TypeOrmModule.forFeature([UserEntity]) to your module imports

@mkelandis your UserModule has to export TypeOrmModule. Then, TypeOrmModule.forFeature([User]) won’t be required

You need to provide UserService in a module. Adding UserService to providers in application.module.ts should work