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

105
Vistas
evite la suscripción anidada si hay un forkjoin dentro

Aquí está mi código en angular

 this.service.save(body).subscribe( resp => { this.dialog.confirmation({ message: 'save object successfully!' }) .subscribe((ok) => { if(ok) { this.pro.status = resp.status; this.loadingData(resp); const s1 = this.service.getSummary(this.id); const s2 = this.service.getCost(this.id); forkJoin([s1, s2]).subscribe([r1, r2]) => { this.view = r1; this.list = r2; } } }); } );

Así que hay muchos niveles de suscripción. No solo es feo, también el resultado es incorrecto y no puedo encontrarlo mediante la depuración. ¿Cómo puedo reescribirlo con operadores rxjs?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Esto debería ser más o menos equivalente:

 this.service.save(body).pipe( mergeMap(resp => this.dialog.confirmation({ message: 'save object successfully!' }).pipe( // This filter acts like your `if(ok)` statement. There's no // else block, so if it's not okay, then nothing happens. The // view isn't updated etc. filter(ok => !!ok), mapTo(resp) ) ), tap(resp => { this.pro.status = resp.status; // If the following line mutates service/global state, // it probably won't work as expected this.loadingData(resp); }), mergeMap(_ => forkJoin([ this.service.getSummary(this.id), this.service.getCost(this.id) ])) ).subscribe([view, list]) => { this.view = view; this.list = list; });
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede simplificarlo usando los operadores RxJS , como el siguiente:

 // import { EMPTY, forkJoin } from 'rxjs'; // import { map, mergeMap } from 'rxjs/operators'; this.service .save(body) .pipe( mergeMap((result) => // Merge the main observable with the dialog confirmation one.. // and map it to an object that contains the result from both observables. this.dialog .confirmation({ message: 'save object successfully!' }) .pipe(map((confirmed) => ({ result, confirmed }))) ), mergeMap(({ result, confirmed }) => { if (confirmed) { this.pro.status = result.status; this.loadingData(result); const s1 = this.service.getSummary(this.id); const s2 = this.service.getCost(this.id); return forkJoin([s1, s2]); } // Don't emit any value, if the dialog is not confirmed: return EMPTY; }) ) .subscribe(([r1, r2]) => { this.view = r1; this.list = r2; });

Nota: Para manejar las fugas de memoria, se recomienda encarecidamente unsubscribe de baja del observable cuando ya no lo necesite, y esto se puede lograr en función de sus casos de uso, como asignar el resultado de la función de subscribe a una variable de Subscription y llamar a unsubscribe de baja en el gancho del ciclo de vida de ngOnDestroy , o usando un Subject con el operador takeUntil y llamando a las funciones next / complete en ngOnDestroy .

Y aquí está cómo usar el método de cancelación de unsubscribe , por ejemplo:

 // import { Subscription } from 'rxjs'; @Component({...}) export class AppComponent implements OnInit, OnDestroy { subscription: Subscription ngOnInit(): void { this.subscription = this.service.save(body) // >>> pipe and other RxJS operators <<< .subscribe(([r1, r2]) => { this.view = r1; this.list = r2; }); } ngOnDestroy() { this.subscription.unsubscribe() } }

Puede leer más sobre eso aquí: https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f

about 4 years ago · Juan Pablo Isaza 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