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

107
Views
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 answers
Answer question

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 Report

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 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!