首页 > 解决方案 > NestJs:从另一个模块导入服务

问题描述

我正在尝试使用surveyServicein voteOptionRepository,但是当我使用路由时,控制台会返回:TypeError: this.surveyService.getSurveyByIdis not a function

这是我的调查模块

    @Module({
    imports: [
        TypeOrmModule.forFeature([SurveyRepository]),
        AuthModule
    ],
    controllers: [SurveyController],
    providers: [SurveyService],
    exports: [SurveyService]
})

export class SurveyModule{}

这是我的 voteOptionModule

@Module({
    imports: [
        TypeOrmModule.forFeature([VoteOptionRepository]),
        AuthModule,
        SurveyModule
    ],
    controllers: [VoteOptionController],
    providers: [VoteOptionService]
})

export class VoteOptionModule{}

这就是我尝试使用该服务的方式

@EntityRepository(VoteOption)
export class VoteOptionRepository extends Repository<VoteOption>{
    constructor(private surveyService: SurveyService){
        super();
    }

    async createVoteOption(createVoteOptionDTO: CreateVoteOptionDTO, surveyId: number, user: User){
        const survey = await this.surveyService.getSurveyById(surveyId, user)
        const { voteOptionName, image } = createVoteOptionDTO;
        
        const voteOption = new VoteOption();

        voteOption.voteOptionName = voteOptionName;
        voteOption.image = image;
        voteOption.survey = survey;

        try{
            await voteOption.save()
            this.surveyService.updateSurveyVoteOptions(voteOption, surveyId, user)
        } catch(error){
            throw new InternalServerErrorException();
        }

        delete voteOption.survey;

        return voteOption;
    }
}

标签: node.jstypescriptnestjs

解决方案


我是 NestJS 的新手,但我相信这是你想要做的。您需要在服务中注入对表的引用。

export class VoteOptionRepository extends Repository<VoteOption>{
    constructor(
       private surveyService: SurveyService
       @InjectRepository
       surveyServiceRepo(SurveyRepository)
      ){
        super();
      }

      async getSurveyById () {
        const survey = await this.surveyServiceRepo.find({id: 'survey-id'})
        return survey
     }
   }

但是,如果没有看到您的 SurveyService,可能是getSurveyById没有正确定义,这就是为什么您会收到错误消息,指出它不是函数。


推荐阅读