Невозможно установить заголовки, потому что запрос на перехват перехватчика перед сохранением токена в локальном хранилище Angular 8 TypeScript - PullRequest
0 голосов
/ 20 апреля 2020

, когда я пытаюсь войти в систему, перехватчики не устанавливают заголовок запроса, потому что он выполняется до блока обслуживания .pipe (), таким образом, currentUser в перехватчиках всегда становится нулевым //////////// ////////////////////////////////////////////////// /

http-interceptor.service.ts

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


    let currentUser = this.logInService.currentUserVal;
    if (currentUser) {
      req = this.addToken(req, currentUser);
    }
    return next.handle(req).pipe(catchError(this.handleError));
  } 

login.service.ts

  public _currentUserSubject: BehaviorSubject<AuthRequest>;
  public currentUser: Observable<AuthRequest>;

  public get currentUserVal(): AuthRequest {
    return this._currentUserSubject.value;
  }

  get currentUserToken() {
    return this.currentUserVal;
  }

  constructor(private httpClient: HttpClient) {

    this._currentUserSubject = new BehaviorSubject<AuthRequest>(this.getUserFromLocalStorage());
    this.currentUser = this._currentUserSubject.asObservable();

  }

  generateToken(authRequest: AuthRequest) {
    return this.httpClient.post<any>(`${this.glolabUrl}${this.authetnticationUrl}`, authRequest, { responseType: 'text' as 'json' })
      .pipe( map(user => {
          localStorage.setItem(this.JWT_TOKEN, JSON.stringify(user));
          this._currentUserSubject.next(user);
          return user;
        })
      );
  }

login.component.ts

    toAuthenticate() {
    this.submitted = true;
    if (this.loginForm.invalid) {
      return;
    }
    this.spinner.show();
    this.authSubscription = this.logInService.generateToken(this.authRequest)
    // .pipe(first())
    .subscribe(
      data => {
        this.logInService.autoritySubject.next(true);
        this.router.navigate(['home']);
        setTimeout(() => {
          this.spinner.hide();
        }, 500);
      },

      err => {
        console.log(err);
        this.spinner.show();
        this.failedMessage = err;
        this.failed = true;
        this.onReset();
        setTimeout(() => {
          this.spinner.hide();
        }, 500);
      }
    );
  }

1 Ответ

0 голосов
/ 21 апреля 2020

вам нужно клонировать ваш запрос в HttpInterceptor, что-то вроде:

  let currentUser = this.logInService.currentUserVal;
    if (currentUser) {
       req = req.clone({
        headers: request.headers.set('Authorization', `Bearer ${currentUser.token}`)

        //req = this.addToken(req, currentUser);
    }
    //return next.handle(req).pipe(catchError(this.handleError));
    return next.handle(req).pipe(
         retry(1),
         catchError((error: HttpErrorResponse) => {
         if (error.status === 401) {
            // refresh token
         } else {
            return throwError(error);
         }
      })
   );
...