在控制器中使用@UseGuards时实现循环依赖时未定义的依赖关系

问题描述 投票:0回答:1

我在我的应用程序中使用 NestJS 并使用

@UseGuards()
。我还为我的控制器创建了 2 个守卫,例如:

JwtAuthGuard:

import { AuthGuard } from '@nestjs/passport';

export class JwtAuthGuard extends AuthGuard('jwt') {}

ApiKeyGuard:

@Injectable()
export class ApiKeyGuard implements CanActivate {
  constructor(private configService: ConfigService) {}

  canActivate (context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    const { apikey } = request.headers;

    if (apikey === env.get('API_KEY')) return true;
    else throw new UnauthorizedException();
  }
}

这是我的控制器:

@Get('/:users')
  @UseGuards(ApiKeyGuard)
  getUser(): {
    return this.userService.getUser();
  }

服务如下:

@Injectable()
export class UserService {
  constructor(private dummyService:DummyService) {}

  getUser() {
    return this.dummyService.getUser();
  }

这是

module.ts
文件:

@Module({
  imports: [...],
  controllers: [userController],
  providers: [....],
  exports: [UserService],
})
export class CouponModule {}

我还有另一个名为

CouponModule
的模块,它也使用
CouponController
及其服务:
@UseGuard()
是与
CouponService
的循环依赖关系,并且也使用
UserService

问题:

当应用程序处理请求时,控制器中具有 DummyService 的所有 API 都会返回错误:

@UseGuards(ApiKeyGuard)

但是当我使用该 API 的 
TypeError: Cannot read property 'getUser' of undefined

时,应用程序工作正常并且没有抛出任何错误。即使我删除了

@UseGuards(JwtAuthGuard)
装饰器,错误又发生了。
我还尝试将 

@UseGuards()

添加到

DummyServices
文件的提供者中,但这并不能解决问题。
我已经做了很多搜索和调查,但仍然找不到任何根本原因或解决方案。

typescript nestjs
1个回答
0
投票
module.ts

,它被注入到

configService
为了确定起见,从构造函数中删除注入。如果运行良好,请检查是否为全局
ApiKeyGuard

© www.soinside.com 2019 - 2024. All rights reserved.