Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

642
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda