我有一个AuthGuard,它检查控制器中的JWT令牌。我想在控制器中使用此Guard来检查身份验证。我遇到这个错误:
嵌套不能解析AuthGuard的依赖项(?,+)。请确保索引[0]的参数在当前上下文中可用。
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();
}
}
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;
}
}
}
答案 0 :(得分:0)
AuthService
(无法解决的依赖项)必须在包含使用防护的控制器的范围内可用。
这是什么意思?
在加载控制器的模块的AuthService
中包含providers
。
例如
@Module({
controllers: [TestController],
providers: [AuthService, TestService, UserService],
})
export class YourModule {}