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
461 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 Reply

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

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

...