我需要找到在后台以角度刷新令牌的方法。
当我必须在本地存储中令牌化时,它的工作很好,但是当令牌在服务器中过期时,它不会加载该页面,因此我需要手动刷新它。我还希望如果用户在本地存储中没有任何内容,则调用该函数并获取新令牌。
这是我的拦截器:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
constructor(public authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.token;
if (!token) {
alert('User Not Authorize');
return next.handle(request);
}
request = request.clone({
setHeaders: {
'Content-Type': 'application/json',
'x-auth-token': token
}
});
return next.handle(request);
}
}
验证服务:
import { Injectable } from '@angular/core';
import { HttpService } from '../http/http.service';
import * as jwt_decode from 'jwt-decode';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpService) { }
authUser(userID) {
if (localStorage.getItem('token') === null) {
this.http.authUser(userID).subscribe((data) => {
localStorage.setItem('token', data.token);
}, error => {
console.log(error);
});
}
}
getCurrentUser() {
try {
const jwt = localStorage.getItem('token');
return jwt_decode(jwt);
} catch (error) {
return null;
}
}
}