我有一个AuthGuard,负责检查控制器中的JWT令牌。我想在控制器中使用此Guard来检查身份验证。我有这个错误:


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


TestController.ts

import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseInterceptors,
  UseGuards,
} from "@nestjs/common";
import { TestService } from "Services/TestService";
import { CreateTestDto } from "Dtos/CreateTestDto";
import { ApiConsumes, ApiProduces } from "@nestjs/swagger";
import { AuthGuard } from "Guards/AuthGuard";

@Controller("/tests")
@UseGuards(AuthGuard)
export class TestController {
  constructor(
    private readonly testService: TestService,
  ) {}

  @Post("/create")
  @HttpCode(HttpStatus.OK)
  @ApiConsumes("application/json")
  @ApiProduces("application/json")
  async create(@Body() createTestDto: CreateTestDto): Promise<void> {
    // this.testService.blabla();
  }
}


AuthGuard.ts

import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { AuthService } from "Services/AuthService";
import { UserService } from "Services/UserService";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private readonly authService: AuthService,
        private readonly userService: UserService,
    ) {}

    async canActivate(dataOrRequest, context: ExecutionContext): Promise<boolean> {
        try {
            // code is here
            return true;
        } catch (e) {
            return false;
        }
    }
}

最佳答案

AuthService(无法解析的依赖项)必须在包含使用防护的控制器的范围中可用。

这是什么意思?

在加载控制器的模块的AuthService中包含providers

例如

@Module({
  controllers: [TestController],
  providers: [AuthService, TestService, UserService],
})
export class YourModule {}


编辑-忘记提及另一种清除方式(也许更清洁,取决于上下文)在于导入提供(exports)服务的模块。

例如

@Module({
  providers: [AuthService],
  exports: [AuthService],
})
export class AuthModule {}

@Module({
  imports: [AuthModule],
  controllers: [TestController],
  providers: [TestService, UserService],
})
export class YourModule {}

关于node.js - Nest无法解析AuthGuard(Guard装饰器)的依赖项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51418222/

10-09 17:41