Executing observables consecutively in Angular without delay

Here are the service calls that I have available:
productService.GetAllProducts()
productService.DeleteProduct()
productService.GetCategories()
productService.DeleteCategory()

In pseudo code, I need to perform the following steps in my component:

  1. Retrieve a list of products using productService.GetAllProducts().

  2. Iterate through the product list and call productService.DeleteProduct() for each product.

  3. After confirming the successful deletion of all products (due to database constraints), I must then get a list of categories using productService.GetCategories(). Iterate through each category and call productService.DeleteCategory().

I understand that having better backend calls for bulk deletes would make my life easier, but unfortunately, I do not have this option. Therefore, I must follow the process of retrieving a list, iterating through it, and deleting each item individually.

Is it feasible to achieve my goal using flatMap and the observable complete parameter? My main challenge lies in determining when all products have been deleted before moving on to search for and delete all categories.

Answer №1

If you're looking to move forward, consider the following approach

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 concept at play here is as follows:

  • GetAllProducts retrieves an array of Products, then serves as input for the initial switchMap
  • Through the use of map, the Products array undergoes transformation into an array of Observables which are outcomes of DeleteProduct – this resulting Observable array is supplied as an argument for the first forkJoin
  • forkJoin produces output upon completion of all the incoming Observables and will signal when every Product has been deleted
  • A similar process applies to handling categories

The code may not be without syntax hiccups, but it should sufficiently point you in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Why is the dateclick event in PrimeNG's FullCalendar not being emitted when clicking on a date? What is the best way to handle click events on specific dates within the calendar?

I am new to using Angular and PrimeNG, and I am facing challenges while trying to implement the FullCalendar component. The specific component I am referring to can be found here: The issue arises when I attempt to trigger an event when a user clicks on a ...

Is it possible to choose the inverse of a user-defined type in Angular?

Is it possible to retrieve the opposite of a specified custom type within a variable using Typescript? For example, if I define a type like this: type Result = 'table' | 'grid'; Then any variable with the type Result can only be assign ...

Form appears outside the modal window

I am facing an issue with my modal where the form inside is displaying outside of the modal itself. Despite trying to adjust the CSS display settings and switching to react-bootstrap from regular bootstrap, the problem persists. I am uncertain about what s ...

How to determine the return type based on the quantity of arguments passed to a rest parameter function

Is there a way to create an arrow function using rest parameters that can return different types based on the number of arguments passed? For example, I am looking to implement a safeId() function with the following return type variations: safeId() // () ...

A Guide to Effectively Managing Express API Responses in Angular 2

When I make an Express API call from my Angular 2 application, I receive a response in the following way. In my component: this.emailService.sendEmail(this.name, this.email, this.message) .subscribe( (res) => ...

How come TypeScript does not detect when a constant is used prior to being assigned?

There's an interesting scenario I came across where TypeScript (3.5.1) seems to approve of the code, but it throws an error as soon as it is executed. It appears that the root cause lies in the fact that value is being declared without being initiali ...

unable to utilize a tip with d3 version 5 in a TypeScript environment?

i'm facing an issue with the following code snippet: var tip = d3.tip() .attr('class', 'd3-tip') .attr('id', 'tooltip') .html(function(d) { return d; }) .direction('n ...

Can a type name be converted into a string representation for use as a template literal type?

Is there a way to retrieve the string representation of a type name in order to return a more concise compile error message from a type function? I came across this solution (unfortunately, the article does not have anchor links so you will need to search ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...

What is the most suitable data type to represent an empty object?

When I declared the return type of the function below as {}, eslint flagged an error stating not to use {} as a type because it actually means "any non-nullish value". After understanding the meaning behind this error, I realize that specifying return typ ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Typescript error: The 'prev' argument does not match the parameter type

Upon implementing this code snippet export const resetErrors = (setErrors: (errors: Array<ErrorInterface>) => void, field: string): void => setErrors((prev: Array<ErrorInterface>): void => prev.filter((el: ErrorInterface) => el.fiel ...

Obtaining the value of an identification number from one service using the identification number from another service

I am currently working on an angular application that retrieves job information, including the customer's name. When storing this data in the jobs table, I make sure to include the customerId within the JobModel. Within my angular job component, I in ...

The Angular overlay is concealed beneath the pinned header

I am seeking a solution to have a mat-spinner displayed on top of my app while it is in the loading state. Currently, I am using an overlay component with Overlay from @angular/cdk/overlay. The issue arises when part of the spinner that should be overlai ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

Can Angular 6 support multiple forms on a single page with unique functions?

In my reactive form, I have all the necessary data for the page or component. However, I also need to store additional information that is not part of the main dataset but is still needed for the component. For instance, I need to keep track of whether Wid ...

What is the process for integrating an extension function into an Express response using TypeScript?

I am looking to enhance the Response object in Express by adding custom functions. Specifically, I want to introduce a function: sendError(statusCode: number, errorMessage: string) which can be called from anywhere like this: response.sendError(500, &qu ...