Issue
I am working with Angular using RxJs, and currently find it very challenging to solve this problem.
I have an array which contains some ids.
ids = [1,2,3,4]
Then I have an API that can be called with the id param, which deletes the item with the given id from the database:
this.controller.deleteItem(id)
I want to call this API on every id in the array.
These API calls should strictly happen one after another in a sequential pattern, like
this.controller.deleteItem(1) -> this.controller.deleteItem(2) etc.
After all of the api calls finished, I would like to fetch the data with:
this.controller.getData()
How can I solve this?
Solution
You can do it using the concat
operator.
First you need to turn the list of IDs into a list of observables, by mapping each item of the array into its corresponding delete action:
const idsToDelete = [1, 2, 3];
const deleteTasks = idsToDelete.map(id => this.controller.deleteItem(id));
Then use concat
to execute the tasks sequentially:
concat(...deleteTasks).subscribe((response) => {
console.log('deleted', response);
});
For getting the data at the end, (assuming that the getData
method also returns an observable) you can insert it at the end, after the deletes, and only listen for the last
response:
concat(...deleteTasks, this.controller.getData()).pipe(
// tap((res) => console.log(res)),
last()
).subscribe((dataAfterDelete) => {
console.log(dataAfterDelete);
});
Answered By - Octavian Mărculescu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.