当我尝试使用拦截器刷新令牌时出现此错误:
错误TypeError:您在期望流的位置提供了“ undefined”。 您可以提供一个Observable,Promise,Array或Iterable。
拦截器:
import { Observable, throwError, from, BehaviorSubject } from 'rxjs';
import { Injectable } from '@angular/core';
import { catchError, map, switchMap, finalize, filter, take } from 'rxjs/operators';
import { HttpInterceptor, HttpRequest, HttpHandler,
HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { AuthService } from '../core/auth/authService/auth.service';
import { ClientError } from '../core/interfaces/errors';
import { IRefreshTokenResponse } from '../core/consts';
import { Storage } from '@ionic/storage';
import { environment } from 'src/environments/environment';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private isTokenRefreshing = false;
tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);
constructor(
private authService: AuthService,
private storage: Storage
) { }
intercept(request: HttpRequest <any> , next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.authService.getToken())
.pipe(switchMap((token: string) => {
console.log('token from interceptor: ', token);
const clonedReq = this.addToken(request, token);
return next.handle(clonedReq).pipe(
map((event: HttpEvent <any> ) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}),
// catchError((error): Observable<any> => {
catchError(error => {
if (error instanceof HttpErrorResponse) {
switch ((error as HttpErrorResponse).status) {
case ClientError.HTTP_401_UNAUTHORIZED:
return this.handleHttpErrorResponse(request, next);
}
} else {
// return throwError(this.handleError);
console.log('error test from else statement: ');
return throwError(error);
}
console.log('error from interceptor: ', error);
console.log('error is: ', error.error.errors);
// return throwError(error);
})
);
})
);
}
// Adds the token to your headers if it exists
private addToken(request: HttpRequest<any>, token: string) {
if (token) {
let clone: HttpRequest<any>;
clone = request.clone({
setHeaders: {
Accept: `application/json`,
'Content-Type': `application/json`,
Authorization: `Bearer ${token}`
}
});
return clone;
}
return request;
}
private handleHttpErrorResponse(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isTokenRefreshing) {
this.isTokenRefreshing = true;
this.tokenSubject.next(null);
console.log('log test from interceptor');
return this.authService.RefreshToken().pipe(
switchMap((tokenResponse: IRefreshTokenResponse) => {
console.log('refresh token response from interceptor: ', tokenResponse);
if (tokenResponse) {
this.tokenSubject.next(tokenResponse.token);
this.storage.set(environment.storage_keys.token, tokenResponse.token);
this.storage.set(environment.storage_keys.refresh_token, tokenResponse.refreshToken);
console.log('token refreshed ...');
console.log('token from refreshing in interseptor: ', tokenResponse.token);
const clonedReq = this.addToken(request, tokenResponse.token);
return next.handle(clonedReq);
}
return this.logout();
}),
catchError(err => {
this.authService.logout();
return this.handleError(err);
}),
finalize(() => {
this.isTokenRefreshing = false;
})
);
} else {
this.isTokenRefreshing = false;
return this.tokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap(token => {
const clonedReq = this.addToken(request, token);
return next.handle(clonedReq);
})
);
}
}
private handleError(errorResponse: HttpErrorResponse) {
let errorMsg: string;
if (errorResponse.error instanceof Error) {
errorMsg = 'An error occured' + errorResponse.error.message;
} else {
errorMsg = `Backend returned code ${errorResponse.status}, body was: ${errorResponse.error}`;
}
return throwError(errorMsg);
}
logout() {
this.authService.logout();
// tslint:disable-next-line: deprecation
return Observable.throw('');
}
}
身份验证服务:
public getToken() {
return this.storage.get(environment.storage_keys.token);
}
public getRefreshToken() {
return this.storage.get(environment.storage_keys.refresh_token);
}
public RefreshToken(): Observable<IRefreshTokenResponse> {
// tslint:disable-next-line: deprecation
return combineLatest<IRefreshTokenResponse>(
from(this.getToken()),
from(this.getRefreshToken())).pipe(
switchMap(([token, refreshToken]: any) => {
// console.log('###tokenn: ', token);
// console.log('###refreshTokenn: ', refreshToken);
const refreshTokenRequest: IRefreshTokenRequest = {token, refreshToken};
console.log('object from refresh token: ', refreshTokenRequest);
return this.http.post<IRefreshTokenResponse>(`${environment.api.baseUrl}${AuthEndPoints.REFRESH_TOKEN}`, refreshTokenRequest);
}),
tap((refreshTokenResponse: IRefreshTokenResponse) => {
console.log('Token response from refresh token: ', refreshTokenResponse);
if (refreshTokenResponse && refreshTokenResponse.token) {
const decoded = jwt_decode(refreshTokenResponse.token);
console.log('decoded from refresh token: ', decoded);
this.userData$.next(decoded);
this.authState$.next(true);
// tslint:disable-next-line: deprecation
const storageObs = combineLatest(
from(this.storage.set(environment.storage_keys.token, refreshTokenResponse.token)),
from(this.storage.set(environment.storage_keys.refresh_token, refreshTokenResponse.refreshToken))
);
return storageObs;
}
})
);
}
我一直在尝试纠正此错误,但是我不知道是什么原因引起的,因此请您提供任何帮助