Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Angular 2 - Chaining http requests

I get a RxJS Observable from an httpService which is the actual http from Angular. Now as soon as I get a postive result from that, I want to process the next http Request which I get from this.retrieve(). This is more or less concattening requests. Is there a better way of doing it?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Chaining HTTP requests can be done using flatMap or switchMap operators. Say we want to make three requests where each request depends on the result of previous one:

this.service.firstMethod()
    .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
    .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
    .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
     });

This way you can chain as much interdependent requests you want.


UPDATE: As of RxJS version 5.5 pipeable operators were introduced and the syntax has slightly changed:

import {switchMap, flatMap} from 'rxjs/operators';

this.service
  .firstMethod()
  .pipe(
    switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
    switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
  )
  .subscribe(thirdMethodResult => {
      console.log(thirdMethodResult);
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...