Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

rxjs - Angular 7 - nesting Observables

I have an Angular route which uses a parameter :client_name, and a service with method getClientDetails(client_name) to fetch data from an HTTP API based on :client_name. Both are Observable methods working on their own, but when I combine the 2 observables then the API call runs before the params has been fetched (client_name is undefined):

    this.route.params.subscribe(params => {
  this.client_name = params['client_name'];
  this.dataService.getClientDetails(this.client_name).subscribe(
    clientdata => {
      this.client = clientdata;
      console.log(clientdata);
    });

How can I chain both observables so the API only runs once the :client_name is returned?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...