在Angular中一个接一个地同步调用可观察对象 [英] Calling observables synchronously one after another in Angular
问题描述
我有以下服务电话:
productService.GetAllProducts()
productService.DeleteProduct()
productService.GetCategories()
productService.DeleteCategory()
I have the following service calls available:
productService.GetAllProducts()
productService.DeleteProduct()
productService.GetCategories()
productService.DeleteCategory()
在sudo代码中,我需要在组件中执行以下操作:
-
使用productService.GetAllProducts()获取产品列表.
Get a list of products using productService.GetAllProducts().
浏览产品列表,并为每个产品调用productService.DeleteProduct().
Loop through the list of products and call productService.DeleteProduct() for each product.
一旦我可以确认上述删除全部完成(由于数据库限制),则需要使用productService.GetCategories()获得类别列表.遍历每个类别并调用productService.DeleteCategory().
Once I can confirm the above deletes are all complete (due to db constraints) I need to then get a list of categories using productService.GetCategories(). Loop through each category and call productService.DeleteCategory().
我知道,如果我有更好的后端调用来进行批量删除,我的生活会轻松很多,但是在这种情况下,我别无选择.我需要遵循获取列表,循环浏览列表,逐个删除每个项目的模式.
I am aware that my life would be a lot easier if I had better backend calls to do bulk deletes, but I do not have a choice in this case. I need to follow the pattern of getting a list, looping through it, doing an individual delete one each item.
使用flatMap和可观察到的完整参数甚至有可能做我想做的事情吗?我最大的问题是在搜索和删除所有类别之前知道代码何时删除所有产品.
Is it even possible doing what I am trying to do using flatMap and the observable complete param? My biggest problem is knowing when the code is finished deleting all of the products before searching for and deleting all of the categories.
推荐答案
您可能想尝试以下方法
productService.GetAllProducts()
.switchMap(
products => forkJoin(products.map(product => productService.DeleteProduct(product)))
)
.switchMap(() => productService.GetCategories())
.switchMap(
categories => forkJoin(categories.map(category => productService.DeleteCategory(category)))
)
.subscribe(() => console.log('done'))
整个想法如下
- GetAllProducts返回一个产品数组,该数组作为
第一个
switchMap
的参数
- 通过
map
将Products数组转换为以下数组: DeleteProduct结果的可观察值-的数组 Observable作为其参数传递给第一个forkJoin
-
forkJoin
在接收到的所有Observables发出时发出 参数完整,因此将在所有产品发布时发出 已被删除 - 对类别重复相同的推理
- GetAllProducts returns an array of Products which is passed as
parameter to the first
switchMap
- The Products array is transformed, via
map
, into an array of Observables which are the result of DeleteProduct - the array of Observable is passed to the firstforkJoin
as its parameter forkJoin
emits when all the Observables it has received as parameter complete, and therefore will emit when all the Products have been deleted- The same reasoning is repeated for categories
我不确定代码在语法上是否完美,但足以让您了解如何进行操作.
I am not sure the code is syntactically perfect, but it should be enough to give you an idea on how to proceed.
这篇关于在Angular中一个接一个地同步调用可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!