Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

641
Views
How to deal with nested subscriptions in Angular, when you might call a void method

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!