3

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,

3 Answers 3

5

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there anyway i can do this so that if the token is expired, it goes to get the token, then sends the request the again and returns that response?
Edited the answer. I throw an error on purpose in order to repeat the whole chain again.
1

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.