NestJS无法解析UserController的依赖项

时间:2018-07-17 16:13:28

标签: typescript nestjs

当前行为

尝试在我的 UserController.ts 中使用我的 UserService.ts AuthService.ts ,但是出现以下错误: [ExceptionHandler] Nest can't resolve dependencies of the UserController (?, +). Please make sure that the argument at index [0] is available in the current context.

通过说明将问题最小化

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 {}
验证服务
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();
  }
...

改变行为的动机/用例是什么?

Bugfix?

环境

嵌套版本:5.1.0 对于工具问题: -节点版本:v8.11.3 -平台:Ubuntu -IDE:VSC

2 个答案:

答案 0 :(得分:1)

您的AuthService必须是您的UserModule的一部分

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

@Module({
   controllers: [
     UserController,
   ],
   components: [
     UserService,
     AuthService
   ],
   imports: [
     AuthModule 
   ]
})
export class UserModule {}

我一直认为import插入某个模块就足够了,但是根据我的经验,我总是不得不在components部分中声明它。

我还意识到您忘记了在组件模块中声明UserService

答案 1 :(得分:0)

自Victor Ivens答复以来,我已经有了这个。

我总是得到一个错误:

  

[ExceptionHandler] Nest无法解析JwtService的依赖项   (?)。请确保索引[0]中的参数可用于   当前上下文。

application.module.ts

const electron = require('electron')
const remote = require('electron').remote
const ipc = require('electron').ipcRenderer
const url = require('url')
const path = require('path')
const app = electron.app
const BrowserWindow = electron.BrowserWindow



var MainWindow;
app.on('ready', function()
{
    MainWindow = new BrowserWindow({
        width: 1024, 
        height: 768, 
        backgroundColor : '123355',
        frame: false,
        resizable: true,
        movable: true,
        show: false
    })
    var win = MainWindow.webContents


    MainWindow.on('ready-to-show', () => {
        MainWindow.show()
        console.log('Ready to go!')
    })

    MainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true

    }))


        win.executeJavaScript("document.onreadystatechange = function ()" +
        "{" +
                "document.getElementById('minimize-app').addEventListener('click', function (e) {" +
                    "var window = BrowserWindow.getFocusedWindow();" +
                    "window.minimize();" +
                "});" +
                "document.getElementById('maximize-app').addEventListener('click', function (e) {" +
                    "var window = BrowserWindow.getFocusedWindow();" +
                    "window.maximize();" +
                "});" +
                "document.getElementById('close-app').addEventListener('click', function (e) {" +
                    "var window = BrowserWindow.getFocusedWindow();" +
                    "window.close();" +
                "});" +
        "}"
        );


});

user.module.ts

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

@Module({
  imports: [
    AuthModule,
    UserModule,
    TypeOrmModule.forFeature([
      UserEntity,
    ]),
    TypeOrmModule.forRoot({
      type: "mysql",
      host: "",
      port: 3306,
      username: "",
      password: "",
      database: "",
      entities: [__dirname + "/../entities/*.entity{.ts,.js}"],
      synchronize: true,
    }),
  ],
  controllers: [
    ApplicationController,
  ],
  providers: [
    ApplicationService,
  ],
})
export class ApplicationModule {}

auth.module.ts

import { Module } from "@nestjs/common";
import { UserController } from "controllers/user.controller";
import { UserService } from "services/user.service";
import { AuthService } from "services/auth.service";
import { AuthModule } from "./auth.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { UserEntity } from "entities/user.entity";

@Module({
  controllers: [
    UserController,
  ],
  components: [
    UserService,
    AuthService,
  ],
  imports: [
    AuthModule,
    TypeOrmModule.forFeature([UserEntity]),
  ],
})
export class UserModule {}