1

I am try to implement refresh token in angular, the problem is the subscribe method of api get executed before getting the refresh token from the api if the token is expired. Here is the snapshot of my code. I don't understand what's wrong i am doing here

 intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    const token = this.storage.getItem(USER_CONST.ACCESS_TOKEN);
    const hasRefreshToken = request.url.includes("refreshToken");
    const httpOptions = {
      headers: new HttpHeaders({
        'content-type': 'application/json',
        'x-channel-id': 'INT',
        'x-trans-id': '1010111111101011111110101111111010111111145241',
        Accept: 'application/json, text/plain, */*'
      })
    };

    if (!hasRefreshToken) {
      httpOptions.headers = httpOptions.headers.set('x-access-token', ` ${token}`);
    } else {
      const refreshToken = this.userService.getRefreshToken();
      httpOptions.headers = httpOptions.headers.set('x-refresh-token', ` ${refreshToken}`);
    }

    const clonedRequest = request.clone(httpOptions)
    return next.handle(clonedRequest)
      .pipe(tap(
        (data) => {
          if (data && data['body'] && data['body']['exception'] && data['body']['exception'][0].description) {
            if (data['body']['exception'][0].name === 'TOKEN_INVALID') {
              const URL = `${environment.API_BASE_URL}${REFRESH_URL}`
              return this.http.post(URL, null, { observe: 'response' })
                .pipe(switchMap(
                  (response: any) => {
                    const exception = response['body'].exception ? response['body'].exception[0] : null;
                    if (exception && (exception.name === 'REFRESH_TOKEN_INVALID' || exception.name === 'REFRESH_TOKEN_EXPIRED')) {
                      return this.router.navigateByUrl('auth/login')
                    }
                    this.userService.setAccessToken(response.headers.get('x-access-token'));
                    this.userService.setRefreshToken(response.headers.get('x-refresh-token'));

                    const requestClone = request.clone();
                    return next.handle(requestClone);
                  }
                ))
            }
          }
        }));
  } 

And this is the subscribe method that gets executed first.

And this is the subscribe method that gets executed first.

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
Rashid
  • 51
  • 1
  • 4
  • Do you mean that your interceptor function fires after callback function from `getUsers`? Put some console.log here to show what exactly fires and which order. Could you also share how you implement the interceptor in DI. – Michał Dziwota Mar 23 '20 at 19:17
  • when i call the getUsers method the interceptor method gets executed it check if the token is invalid then it post refresh token api but instead of calling ".pipe(switchMap())" the subscribe call back of getUser executed and it finish. It should execute ".pipe(switchMap())" of post to refresh method – Rashid Mar 23 '20 at 19:38
  • @MichałDziwota i have tried switchMap, flatMap, mergeMap but i don't know why it does not return, i have to get refresh token and proceed the furthur calls. – Rashid Mar 23 '20 at 19:42
  • The first pipe you used is `tap` which doesn't expect any return, change it to `switchMap` also to change the target of subscription. Also, avoid calling `next.handle` function twice, its bad practice. – Michał Dziwota Mar 24 '20 at 21:15

0 Answers0