代码之家  ›  专栏  ›  技术社区  ›  pirmax

Nest无法解析authGuard(Guard decorator)的依赖项

  •  1
  • pirmax  · 技术社区  · 7 年前

    我有一个authguard检查控制器中的jwt令牌。我想在控制器中使用这个守卫来检查身份验证我有个错误:

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

    测试控制器.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;
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   VinceOPS    6 年前

    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 {}
    
    推荐文章