Angular 7 – nesting Observables

We can make use of pipeable RxJS operators for this scenario.

First, we can use RxJS’s mergeMap to map over the observable values from route into an inner observable. If params and params['client_name'] are defined, we assign params['client_name'] to the client_name property, which is similar to your initial code. Then, we call the getClientDetails() method from dataService. If the params do not exist, we convert null into an observable, and return it.

Subsequently, the observables are returned in .subscribe() block. From there, we can assign the response to the client property.

import { mergeMap } from 'rxjs/operators';
import { of } from 'rxjs';
.
.
this.route.params.pipe(
  mergeMap(params => {
    if (params && params['client_name']) {
      this.client_name = params['client_name'];
      return this.dataService.getClientDetails(this.client_name);
    } else {
      return of(null)
    }
  })
).subscribe(response => {
  // handle the rest
  this.client = response;
})

Leave a Comment