Winston Zhao
Winston Zhao

Reputation: 79

Sending two HTTP Requests one after each other using Angular / RXJS where second request requires the first?

Currently my code this by nesting observables inside each other...

makeRequest() {
  return this.http.get().map((response: Response) => {
    return this.http.get(response.doSomething());
  }
}

When I need to use it, I subscribe to them both using nesting as well...

I'm fairly sure this isn't the correct way and right now I need a way to do something along the lines of this:

-> make request -> check reply -> if reply indicates token is outdated -> get new token and do the request again -> else pass the results on

What would be the recommended way to achieve this?

Many Thanks,

Upvotes: 3

Views: 10084

Answers (3)

Fan Cheung
Fan Cheung

Reputation: 11345

Use flatMap or switchMap and conditionally return different Observable

auth() {
  return this.http.get().flatMap((response: Response) => {
  if (token not expire....) {
  // pass on the response
    return Observable.of(response)
  }
    return this.http.get(response.getToken()).mapTo(Observable.throw('Retry'));
  }).retry()
}

Upvotes: 5

Maged Milad
Maged Milad

Reputation: 311

I think you can use async.js waterfall

async.waterfall([
 function(callback) {
   this.http.get(url1).then(res1 => {
     callback(null, res1); 
   }).catch(err => {
     callback(err);
   })
 },
 function(res1, callback) {
    this.http.get(url2).then(res2 => {
     callback(null, res2); 
   }).catch(err => {
     callback(err);
   })
 },
], function (err, result) {
   // result now equals res2
   // err here is the first error occure
});

here the first callback request will happen first then the second one depending on the result of the first one, so if the first fails the second request won't occur, and you can chain any number of depending request like that

or you can use async await pattern to do this

Upvotes: -1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41377

we use the mergeMap/flatMap to iterate over an observable. mergeMap will pull the observable from inner observable and pass it to the parent stream.

 makeRequest() {
    return this.http.get().pipe(
      mergeMap(response: Response => this.http.get(response.doSomething())
    );
  }

Upvotes: 1

Related Questions