Search code examples
angularrxjsgraphqlangular-routerrxjs-pipeable-operators

Implement RxJs operator instead of nested subscribe blocks


I'm getting an id from the route params and that I'm passing to my API call. For this, I'm currently using nested subscription. But I want to use the concat() or maybe some other operator of RxJs(I don't know which) so that I can avoid nesting. Since the docs here is not giving some example, which left me confused regarding, how I can use it here in my code.

Below is code where nesting is implemented, I want to implement same logic using concat() or maybe some other operator of 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);
        }
      });
  }
});

Solution

  • The operator you really want is 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);
            }
        });