【问题标题】:Use module service into entity NestJS在实体 NestJS 中使用模块服务
【发布时间】:2020-11-25 14:21:45
【问题描述】:

在 NestJS API 上,我想在实体中使用模块服务来使用非数据库属性填充该实体。

就我而言,我想获取我正在检索的类别的文章数。

@Entity({ name: 'categories' })
export class Category {
    constructor(private readonly service: CategoriesService) { }

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    @Index({ unique: true })
    title: string;

    @OneToMany(() => Article, articles => articles.category)
    articles: Article[];

    numberOfExercices: number;

    @AfterLoad()
    async countExercices() {
        this.numberOfExercices = await this.service.getNumberOfArticles(this.id);
    }
}

但我收到此错误:

Nest can't resolve dependencies of the GlobalPrevCategoriesService (GlobalPrevCategoriesRepository, ?).
Please make sure that the argument dependency at index [1] is available in the GlobalPrevCategoriesModule context.

我尝试了这个小变种,但我得到了同样的错误。

constructor(
    @Inject(GlobalPrevCategoriesService)
    private readonly service: GlobalPrevCategoriesService) { }
)

这是我的模块:

@Module({
    imports: [
        TypeOrmModule.forFeature([CategoriesRepository]),
        ArticlesModule
    ],
    controllers: [CategoriesController],
    providers: [CategoriesService],
    exports: [CategoriesService]
})
export class CategoriesModule { }

是否可以在实体中使用服务?

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    我认为不可能将服务注入实体。 ORM 模块(例如,TypeORM)实例化实体。而且 ORM 不知道 NestJs 框架中的依赖注入机制。

    您可以在 TypeORM 中查看Active-Record pattern。它解决了您在加载后获取与类别实例相关的文章数量的问题。但它不能帮助您将 CategoriesService 注入到您的 Category 实体中。

    一般来说,将服务类注入实体类并不是一个好主意。

    【讨论】:

    • 谢谢。我在处理 TypeOrm innerJoin() 方法时遇到了一些麻烦,但现在使用 Active-Record 模式可以正常工作。
    猜你喜欢
    • 2019-09-13
    • 2019-04-25
    • 2021-08-30
    • 2019-12-26
    • 2020-07-08
    • 2022-09-27
    • 2022-08-08
    • 2021-04-01
    • 2022-12-24
    相关资源
    最近更新 更多