我创建了一个功能模块“用户”。在这个模块中,我创建了控制器、模型和服务来连接到我的 postgres 数据库。 但是,如果我尝试从我的功能模块控制器调用 userService,我会收到以下错误
[RpcExceptionsHandler] Cannot read property 'get_users' of undefined
TypeError: Cannot read property 'get_users' of undefined
at UserController.get (/usr/src/app/dist/user/controller/user.controller.js:23:33)
at /usr/src/app/node_modules/@nestjs/microservices/context/rpc-context-creator.js:44:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async /usr/src/app/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32
at async ServerTCP.handleMessage (/usr/src/app/node_modules/@nestjs/microservices/server/server-tcp.js:55:54)
下面是我的 user.controller.ts 文件:
import { Logger } from '@nestjs/common';
import { UserI } from '../models/user.interface';
import { UserService } from '../service/user.service';
import { MessagePattern } from '@nestjs/microservices';
export class UserController {
private logger = new Logger('AppController');
constructor(private readonly userService: UserService) {}
@MessagePattern('add_user')
async add(user: UserI) {
return this.userService.add(user);
}
@MessagePattern('get_user')
async get() {
return this.userService.get_users();
}
}
user.service.ts:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { from } from 'rxjs';
import { Repository } from 'typeorm';
import { UserEntity } from '../models/user.entity';
import { UserI } from '../models/user.interface';
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>
) {}
add(user: UserI) {
return this.userRepository.save(user);
}
get_users() {
return this.userRepository.find();
}
}
用户.module.ts:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './controller/user.controller';
import { UserEntity } from './models/user.entity';
import { UserService } from './service/user.service';
@Module({
imports:[
TypeOrmModule.forFeature([UserEntity])
],
providers: [UserService],
controllers: [UserController]
})
export class UserModule {}
app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { UserModule } from './user/user.module';
@Module({
imports: [
ConfigModule.forRoot({isGlobal:true}),
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_URL,
autoLoadEntities: true,
synchronize: true
}),
UserModule
],
controllers: [],
providers: [],
})
export class AppModule {}
you should mark
UserController
as a controller 以便能够在其中注入思想。只需在您的 @Controller()
课程中添加 UserController
即可。
https://docs.nestjs.com/controllers
看起来
UserController
是从 AppModule
捡到的。你应该只在一个模块文件中定义你的提供者和控制器,否则你最终会覆盖一些元数据。从UserController
中删除AppModule
,只保留到UserModule
。它应该从那里解决你的问题。