简体   繁体   English

angular rxjs mergeMap/flatMap 而不是多个管道/订阅

[英]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.请给我举个例子,如何使用像 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;
          });
      });
  });

} }

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另外,我绝对不会使用 any 作为类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM