在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
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.
Run Code Online (Sandbox Code Playgroud)
我尝试了这个小变体,但遇到了同样的错误。
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.
Run Code Online (Sandbox Code Playgroud)
这是我的模块:
constructor(
@Inject(GlobalPrevCategoriesService)
private readonly service: GlobalPrevCategoriesService) { }
)
Run Code Online (Sandbox Code Playgroud)
在实体中使用服务是否可能?
我认为向实体注入服务是不可能的。ORM 模块(例如 TypeORM)实例化实体。ORM 不知道 NestJs 框架中的依赖注入机制。
您可以在 TypeORM 中检查Active-Record 模式。它解决了您在加载后获取与类别实例相关的文章数量的问题。但它并不能帮助您将 CategoryService 注入到您的 Category 实体中。
一般来说,将服务类注入到实体类中并不是一个好主意。
| 归档时间: |
|
| 查看次数: |
4160 次 |
| 最近记录: |