'how to inject service in guard? (nestjs)

I'm implementing a code that authenticates users through guard.

So I want to inject AuthService in JwtAuthGuard.
but I'm not solving this error right now.

I keep getting errors like comment in the jwt-auth.guard.ts.

this is my code.

jwt-auth.guard.ts

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') implements CanActivate {
  constructor(
    @Inject(AuthService)
    private readonly _authService: AuthService
  ) {
    super();
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

    const { authorization } = request.headers;
    if (authorization === undefined) {
      return false;
    }

    const token = authorization.replace('Bearer ', '');
    const result = this.validate(token);

    console.log(result); // error

    return result;
  }

  async validate(token: string) {
    console.log(this._authService); // this is undefined
    try {
      await this._authService.validateToken(token); // TypeError: Cannot read properties of undefined (reading 'validateToken')
      return true;
    } catch (e) {
      return e;
    }
  }
}

auth.service.ts

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  async validateToken(token: string) {
    return await this.jwtService.verify(token, {
      secret: JWT_SECRET,
    });
  }
}

auth.module.ts

@Module({
  imports: [
    UserModule,
    JwtModule.register({
      secret: JWT_SECRET,
    }),
  ],
  providers: [AuthService, KakaoStrategy, NaverStrategy, GoogleStrategy],
  controllers: [AuthController],
  exports: [AuthService]
})
export class AuthModule {}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source