我使用以下基于类的拦截器来刷新用户令牌:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private inject: Injector) {}
intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
let tokenService = this.inject.get(TokenService);
let authReq = request;
authReq = this.AddTokenHeader(request, tokenService.getAccessToken())
return next.handle(authReq).pipe(
catchError(errorData => {
if (errorData.status == 401) {
return this.handleRefreshToken(request, next);
}
return throwError(errorData);
})
);
}
AddTokenHeader(request: HttpRequest < any > , token: any) {
return request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + token)
});
}
handleRefreshToken(request: HttpRequest < any > , next: HttpHandler) {
let tokenService = this.inject.get(TokenService);
let authService = this.inject.get(AuthService);
let sessionStorageService = this.inject.get(SessionStorageService);
var refreshTokenVM = new RefreshTokenVM();
refreshTokenVM.UserId = tokenService.getUserId();
refreshTokenVM.RefreshToken! = tokenService.getRefreshToken() !;
return tokenService.refreshToken(refreshTokenVM).pipe(
switchMap((data: any) => {
sessionStorageService.saveData('accessToken', data.accessToken);
sessionStorageService.saveData('refreshToken', data.refreshToken);
return next.handle(this.AddTokenHeader(request, data.accessToken))
}),
catchError(errorData => {
authService.logout();
return throwError(errorData);
})
);
}
}
在 Angular 17 中,我们必须使用函数式拦截器。我尝试将上面的代码转换为功能拦截器:
export const authInterceptor: HttpInterceptorFn = (request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> => {
const clonedRequest = request.clone({
setHeaders: {
Authorization: 'Bearer ' + 'token',
}
});
return next(clonedRequest).pipe(
catchError(errorData => {
if (errorData.status == 401) {
}
return throwError(() => errorData);
})
);
};
问题是我无法注入tokenService
拦截器函数(我将令牌存储在SessionStrorage
)。另外,我不知道如何handleRefreshToken
在功能拦截器中集成功能。我怎么解决这个问题?
TokenService
您应该能够使用注入功能进行访问: