TypeError: Cannot read properties of undefined when call method of injected provider in NestJS

Viewed 10

Follow tutorial at here, I'm just implement simple NestJS app with a module have injected provider below:

# app.module.ts

import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

import { AuthModule } from '@/modules/auth/auth.module'

@Module({
  imports: [
    ConfigModule.forRoot(),
    AuthModule
  ]
})
export class AppModule {}

# auth.module.ts

import { Module } from '@nestjs/common'

import { AuthController } from '@/modules/auth/auth.controller'
import { AuthService } from '@/modules/auth/auth.service'

@Module({
  controllers: [AuthController],
  providers: [AuthService]
})
export class AuthModule {}

# auth.controller.ts

import { Controller, Get } from '@nestjs/common'
import { AuthService } from '@/modules/auth/auth.service'

@Controller('auth')
export class AuthController {
  constructor (private readonly service: AuthService) {}

  @Get('me')
  public getSelfInfo (): string {
    return this.service.getSelfInfo()
  }
}
# auth.service.ts

import { Injectable } from '@nestjs/common'

@Injectable()
export class AuthService {
  getSelfInfo (): string {
    return 'ok'
  }
}

But when call to endpoint, this error thrown:

[Nest] 17196 - 09/23/2022, 2:34:18 PM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getSelfInfo') TypeError: Cannot read properties of undefined (reading 'getSelfInfo') at AuthController.getSelfInfo (/dist/modules/auth/auth.controller.js:16:29)

Please tell me which problem at here.

1 Answers

Solved this issue when add code block below to app.controller.ts:

@Inject(AuthService)
private readonly service: AuthService

constructor (service: AuthService) {
  this.service = service
}
Related