I have the following code:
this.rolesService.addEmployeeRoles(addDtos).subscribe(
() => {
if (removeIds.length > 0) {
this.rolesService.removeEmployeeRoles(removeIds).subscribe(
this.bsModalRef.hide,
error => console.log('error' + error));
}
else
this.bsModalRef.hide();
},
error => console.log('error' + error));
How can this be rewritten so I don't have to use nested subscriptions? I was looking at examples online, but I'm not sure how I would handle the else part here which calls a void method.
I have been looking at examples of flatmap I'm not sure how to apply them in this usecase.
You could use flatMap or for example switchMap. As we we only need one inner subscription, I would go with switchMap. SwitchMap expects to an observable to be returned, you can just use of to create a dummy observable. I am not using EMPTY here as we want to perform a side effect after switchMap, i.e closing the modal. So I would suggest the following:
import { of } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators'
//....
this.rolesService.addEmployeeRoles(addDtos).pipe(
switchMap(() => {
if (removeIds.length > 0) {
return this.rolesService.removeEmployeeRoles(removeIds)
}
return of('whatever');
}),
tap(_ => this.bsModalRef.hide())
).subscribe();
Alternatively you can return EMPTY when not making api call and close the modal inside subscribe.