Nest 无法解析 AuthGuard(Guard 装饰器)的依赖项

Nest can't resolve dependencies of the AuthGuard (Guard decorator)

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

Nest can't resolve dependencies of the AuthGuard (?, +). Please make sure that the argument at index [0] is available in the current context.

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(无法解析的依赖项)必须在包含使用守卫的控制器的范围内可用。

什么意思?

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

例如

@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 {}