TypeError:在NestJS中调用注入的提供程序的方法时,无法读取未定义的属性



按照这里的教程,我只是用一个模块来实现简单的NestJS应用程序。下面已经注入了提供程序:

# 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'
}
}

但当调用端点时,抛出了以下错误:

[Nest]17196-2022年9月23日下午2:34:18错误[ExceptionsHandler]无法读取未定义的属性(读取"getSelfInfo"(TypeError:无法读取未定义的属性(正在读取"getSelfInfo"(在AuthController.getSelfInfo(/dist/modules/auth/auth.controller.js:16:29(

请告诉我这里的哪个问题。

在将以下代码块添加到app.controller.ts:时解决了此问题

@Inject(AuthService)
private readonly service: AuthService
constructor (service: AuthService) {
this.service = service
}

当我添加

"类型":"模块">
到我的package.json,因为我需要使用ES模块。

我必须更新所有导入并将扩展添加到路径中。

从"导入{ProductsService}/产品.服务
变为
从"导入{ProductsService}/products.service.js'

在那之后,我遇到了同样的问题,就像@Dan Tran。他的解决方案有效,但我必须重构我的整个项目。

这是唯一的解决方案吗?还是缺少什么?因为周说这不应该是必要的。

最新更新