简体   繁体   中英

Chaining rxjs operators

I have a function called fetch which is implemented like this:

fetch(): Observable<Option> {
    return this.clientNotebookService.getClientNotebook()
      .pipe(
        map(
          clientNotebook => {
            this.person = _.find(clientNotebook.persons, i => i.isn === this.isn);
            return {
              value: this.person.address['TownIsn'],
              name: this.person.address['TownName']
            };
          }
        )
      );
}

where person is of type RelatedPerson and isn if of type string . The problem with this function is that it doesn't know anything about isn , that's to say, isn should be provided to it in some way.

This value can be extracted in the following way:

this.activatedRoute.params.subscribe(
    params => this.isn = params['id']
)

And I would like to do this within the fetch method by combining rxjs operators.

You can chain them like below, just extract the 'id' and pass it to fetch

const isn=this.activatedRoute.params.pipe(pluck('id'))
isn.pipe(mergeMap(isn=>fetch(isn)))

Then add a param to your fetch, then it is available inside the function

fetch(isn){ .....

You can use combineLatest that emits an array of the latest value from both streams every time either emit a value

combineLatest(
  this.activatedRoute.params.pipe(map(params => params['id'])),
  this.clientNotebookService.getClientNotebook()
).pipe(map(([isn, clientNotebook]) => {
  this.person = clientNotebook.persons.find(p => p.isn === isn); // No need for _
  return {
    value: this.person.address['TownIsn'],
    name: this.person.address['TownName']
  };
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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