实现 RxJs 运算符而不是嵌套的订阅块

Implement RxJs operator instead of nested subscribe blocks

我从 路由参数 得到一个 id 并且我正在传递给我的 API 调用。为此,我目前正在使用 嵌套订阅 。但是我想使用 concat()RxJs 的其他运算符(我不知道是哪个),这样我就可以避免嵌套。由于文档 here 没有给出一些示例,这让我很困惑,我该如何在我的代码中使用它。

下面是实现嵌套的代码,我想使用 concat() 或者 RxJs 的其他运算符来实现相同的逻辑。

this.route.params.subscribe((params: Params) => {
  this.selectedPostId = +params['id'];
  if (this.selectedPostId) {
    // Simple GraphQL API call below
    this.apollo.watchQuery(GetPost, {id: this.selectedPostId})
      .subscribe((post: PostType) => {
        if (post) {
          console.log(post);
        }
      });
  }
});

您真正想要的运算符是flatMap

import { map, flatMap, filter } from 'rxjs/operators';

// ...


this.route.params.pipe(
        map((params: Params) => +params['id']), // Get the ID param
        filter((selectedPostId: any) => selectedPostId), // Remove any events without an ID
        flatMap(id => this.apollo.watchQuery(GetPost, {id: selectedPostId})) // Call the watchQuery function
    ).subscribe((post: PostType) => {
        if (post) {
          console.log(post);
        }
    });