gpt4 book ai didi

javascript - 当 JWT token 在 Angular 7 中过期时如何显示警报或 toastr 消息

转载 作者:太空狗 更新时间:2023-10-29 18:27:45 25 4
gpt4 key购买 nike

当 JWT token 过期时,Web 应用程序应显示一个警报 或模式弹出窗口,然后它应重定向到登录页面。目前我正在使用 toastr 消息。

我的组件中有很多 api 调用。我收到许多 toastr 消息“ token 已过期”。我应该只显示一条消息并重定向到登录页面。告诉我你的好主意。我在互联网上有一些文章。但是我无法清楚地了解那些东西。

import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ToastrManager } from 'ng6-toastr-notifications';
import { Injectable } from '@angular/core';
import { JwtDecoderService } from './jwt-decoder.service';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

constructor(public router: Router,
public toastr: ToastrManager,
private jwtDecoder: JwtDecoderService, ) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (localStorage.getItem('isLoggedin') === 'false' && !this.jwtDecoder.isTokenExpired()) {
this.toastr.warningToastr('Token expired');
return;
}
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
if (error.status === 404) {
this.toastr.warningToastr('Server Not Found');
this.router.navigate(['/login']);
}
if (error.status === 412) {
this.toastr.warningToastr('Token expired');
this.router.navigate(['/login']);
}
// if (error.status === 500 || error.status === 400) {
// this.toastr.errorToastr('We encountered a technical issue');
// }
}
// return throwError(errorMessage);
return throwError(error);
})
);
}
}

最佳答案

您可以使用HttpInterceptor。由于每个 API 调用都通过拦截器,您可以检查 token 是否仍然有效,继续 API 调用

如果 token 过期,显示 toastr 警报并阻止任何进一步的 API 调用。

有关使用拦截器的更多信息,请访问此 10 ways to use Interceptors Angular 7 JWT Interceptor

Complete Code:

http-interceptor.service.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { SessionService } from './session.service';
import { Router } from '@angular/router';
import { throwError } from 'rxjs';

declare var toastr;

@Injectable({
providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

constructor(private router: Router, private sessionService: SessionService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
var token = this.sessionService.getToken();
if (token != null && this.sessionService.isTokenExpired()) {
this.sessionService.logOut()
toastr.warning("Session Timed Out! Please Login");
this.router.navigate(['/login'])
return throwError("Session Timed Out")
} else {

const authRquest = req.clone({
setHeaders: {
Authorization: 'Bearer ' + token
}
})
return next.handle(authRquest)
.pipe(
tap(event => {
}, error => {
})
)
}

}
}

app.module.ts

 providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true
}
]

session-service.ts

  getToken(): string {
return localStorage.getItem('userToken');
}

getTokenExpirationDate(token: string): Date {
token = this.getToken()
const decoded = jwt_decode(token);

if (decoded.exp === undefined) return null;

const date = new Date(0);
date.setUTCSeconds(decoded.exp);
return date;
}

isTokenExpired(token?: string): boolean {
if (!token) token = this.getToken();
if (!token) return true;

const date = this.getTokenExpirationDate(token);
if (date === undefined) return false;
return !(date.valueOf() > new Date().valueOf());
}

logOut(loginType?: string) {
localStorage.removeItem('isLoggedin');
localStorage.removeItem('userRole');

}

关于javascript - 当 JWT token 在 Angular 7 中过期时如何显示警报或 toastr 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com