我尝试在 nestjs 文档和 github 以及这个问题上寻找答案:Nestjs Dependency Injection - Inject service into service,但找不到任何答案,只有循环依赖。我有产品服务:
products.service.ts
@Injectable()
export class ProductsService {
constructor(@InjectModel(Product.name) private productModel: Model<ProductDocument>) {}
// TODO: return string переделать
async create(createProductDto: CreateProductDto): Promise<Product> {
// TODO: need call CategoriesService.findOne(createProductDto.id) to check exist categories by id
const createdProduct = new this.productModel(createProductDto);
return createdProduct.save();
}
}
在 products.module.ts i 并添加到导入数组类别模块
products.module.ts
@Module({
imports: [
MongooseModule.forFeature([
{ name: Product.name, schema: ProductSchema },
]),
// add CategoriesModule
CategoriesModule,
],
controllers: [ProductController],
providers: [ProductsService],
})
export class ProductModule {}
categories.module.ts
@Injectable()
export class CategoriesService {
constructor(@InjectModel(Category.name) private categoryModel: Model<CategoryDocument>) {}
async findOne(@Param('id') id: string): Promise<boolean> {
// need only check exist category
const exist = await this.categoryModel.findOne({ id }, { _id: true });
if (exist) {
return true;
}
return false;
}
}
请告诉我如何正确调用另一个模块的服务方法
答案 0 :(得分:0)
在 products.service.ts 我添加私有变量类别服务,然后调用这个
constructor(@InjectModel(Product.name) private productModel: Model<ProductDocument>, private readonly categoriesService: CategoriesService) {}