При реализации механизма токена refre sh фактический вызов выполняется до получения токена refre sh - PullRequest
0 голосов
/ 23 марта 2020

Я пытаюсь внедрить токен refre sh в angular, проблема заключается в том, что метод подписки api выполняется перед получением токена refre sh от API, если токен истек. Вот снимок моего кода. Я не понимаю, что не так, я делаю здесь

 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.

...