Calling observables synchronously one after another in Angular

前端 未结 1 1442
囚心锁ツ
囚心锁ツ 2021-01-26 18:51

I have the following service calls available:
productService.GetAllProducts()
productService.DeleteProduct()
productService.GetCategories()
prod

1条回答
  •  有刺的猬
    2021-01-26 19:46

    You may want to try something along these lines

    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'))
    

    The whole idea is the following

    • 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 first forkJoin 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.

    0 讨论(0)
提交回复
热议问题