簡體   English   中英

angular rxjs mergeMap/flatMap 而不是多個管道/訂閱

[英]angular rxjs mergeMap/flatMap instead of multiple pipe/subscribe

下面是一個代碼示例。 請給我舉個例子,如何使用像 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;
          });
      });
  });

}

你可以試試下面的代碼

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;
        });
}

另外,我絕對不會使用 any 作為類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM