我使用angular 7拦截器处理我的错误,如果错误是400,但我想刷新令牌,但我遇到了错误。我想使用我的服务来刷新interceptor-catchError中的令牌。我尝试了很多方法但没有成功。 我认为这不是好方法。请帮我。预先感谢
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.returnResponseAfterUserLoginService.currentUserValue();
let currentToken = this.returnResponseAfterUserLoginService.currentTokenValue();
let token = this.localStorageService.getFromLocal('token')
// if (currentUser && currentToken) {
if (currentToken) {
request = request.clone({
setHeaders: {
Authorization: `JWT ${currentToken}`
}
});
}
// return next.handle(request);
return next.handle(request)
.pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error instanceof HttpErrorResponse) {
switch (error.status) {
case 416:
return this.handle416Error(error)
case 400:
return this.handle400Error(error, request)
case 401 || 403:
return this.handle401Error(error)
}
}
// return throwError(error)
})
)
}
handle400Error(error, request) {
if (error) {
if (error.status === 400 && error.error.non_field_errors[0] === 'Signature has expired.') {
const currentToken = this.localStorageService.getFromLocal('token');
const isLogged = this.returnResponseAfterUserLoginService.currentIsLoggedValue();
console.log('Signature has expired.');
// it doesn't works
this.userService.refreshToken(currentToken).subscribe(
x=>{
if(x && x['token'])
console.log(x);
},
err =>{
console.log(err);
this.router.navigate(['/login'], { queryParams: { redirectURL: this.router.url } })
}
)