1
votes

I am learning Rxjs and working on ionic 4 app which uses ionic-native http plugin for api calling(It returns promise).I am using below code for making API call/refresh token logic.

Utility file code:(Using from operator to convert promise into observable)

from(this.http.get(url, param, headerMap)); 

Service file code

return this.utilService.httpCall2('GET', taskURL, null, null).pipe(catchError(err=>{
        if(err.status==401){
          // return  this.utilService.refreshTokenAndRetryCall2().toPromise().then(()=>{
          //   return this.utilService.httpCall2('GET', taskURL, null, null);
          // });
          return this.utilService.refreshTokenAndRetryCall2()
        }
        else{
          throw err;
        }
      }
    ),
      tap(resp => console.log("API response is", JSON.stringify(resp))), map(resp => JSON.parse(resp.data)),
      tap(resp => console.log("parsed data is ", JSON.stringify(resp))));

I want to achieve below scenario

  1. Call API using utility http method this.utilService.httpCall2('GET', taskURL, null, null).
  2. If the token is expired then API returns 401 and call refresh token method.
  3. After refresh token call original api again to get the desired data

So the issue I am facing is after refreshTokenAndRetryCall2() call I am not able to do the original api call with refresh token(i.e, this.utilService.httpCall2('GET', taskURL, null, null)

1

1 Answers

0
votes

So the catchError operator actually has two parameters error & source. Source represents the source observable, so what you could do is

return this.utilService.httpCall2('GET', taskURL, null, null).pipe(catchError((err, source) =>{
        if(err.status==401){
          return  this.utilService.refreshTokenAndRetryCall2().pipe(
            switchMapTo(source)
          )
        }
       ...

Just remember to build in some kind of circuit breaker otherwise you might end up in an endless loop