mergeMap to Turn Values into Subscribed Observables
mergeMap(value => observable) will subscribe and emit the value of the mapped observables for you. It looks like all you need is mergeMap(body => service(body)) and you're off to the races.
The following is a pretty direct translation of what you're doing with RxJS. If your code works, then (in theory, I can't test it) this or something very similar should work.
I'm not sure where body is defined in your example, so I'll pretend it's an object with some properties and you're adding another property (name) to it
addItems(){
range(1, this.count).pipe(
map(i => ({
...body,
name: `${this.createItemForm.get('name').value}-${i}`
})),
mergeMap(body => this.cvmService.createServer(body))
).subscribe({
next: resp => {
this.alertify.success('New item was successfully created');
this.close(true);
},
error: err => this.alertify.error('\n' + err),
complete: () => console.log(`${this.count} items where succesfully created`)
});
}
forkJoin to Turn Array of Observables into Array of Responses
The same thing can be done with forkJoin since it looks like your service calls emit once and complete.
Here, you first need to create an array of the service calls you want. I do this by mapping an array [1,2,3,4,5] into body objects [{name:worker-1},{name:worker-2},{name:worker-3},{name:worker-4},{name:worker-5}] and then mapping body objects into service calls [observable,observable,observable,observable,observable].
All that is done without any RxJS, the RxJS part is the forkJoin([observable,observable,...]). Which subscribes to every observables and wait for them all to complete.
The difference is that forkJoin will emit the final results as an array. If you still want an alert and a call to this.close(true) for each result, then we'd need to instrument each service call (source observable in the array) to do that.
When you subscribe, the next callback will be given an array. The implementation looks like this:
addItems(){
forkJoin(
Array.from(
{length: this.count},
(_,i) => i+1
).map(i => ({
...body,
name: `${this.createItemForm.get('name').value}-${i}`
})).map(body =>
this.cvmService.createServer(body).pipe(
tap(_ => {
this.alertify.success('New item was successfully created');
this.close(true);
})
)
)
).subscribe({
next: resp => {
console.log(`${resp.length} items where succesfully created`);
},
error: err => this.alertify.error('\n' + err)
});
}