Sergej
Sergej

Reputation: 2176

angular rxjs mergeMap/flatMap instead of multiple pipe/subscribe

Below is an example of code. Show me please an example, how this code can be improved using features like mergeMap/combine observables.

ngOnInit() {
this.route.params
  .pipe(takeUntil(this.destroy$))
  .subscribe((params: any) => {
    this.getRound(params.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe((round: any) => {
        this.round = round;
        this.getStats(params.id, round.required_tickets)
          .pipe(takeUntil(this.destroy$))
          .subscribe((stats: any) => {
            this.stats = stats;
          });
      });
  });

}

Upvotes: 0

Views: 315

Answers (1)

Ben Ari Kutai
Ben Ari Kutai

Reputation: 559

You can try the code below

ngOnInit() {
    this.route.params
        .pipe(
            takeUntil(this.destroy$),
            switchMap((params: any) => {
                this.params = params
                return this.getRound(params.id)
            }),
            switchMap((round: any) => {
                this.round = round;
                return this.getStats(this.params.id, round.required_tickets)
            })
        )
        .subscribe((stats: any) => {
            this.stats = stats;
        });
}

Plus, I would definitely not use any as types

Upvotes: 2

Related Questions