You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.8 KiB
82 lines
2.8 KiB
import { Injectable } from '@angular/core'; |
|
import { |
|
HttpClient, HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, |
|
HttpErrorResponse |
|
} from '@angular/common/http'; |
|
import { throwError } from 'rxjs' |
|
import { catchError, retry } from 'rxjs/operators'; |
|
import { Router,ActivatedRoute } from '@angular/router' |
|
import { CacheTokenService } from './cache-token.service' |
|
import { IsLoginService } from '../is-login.service' |
|
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar'; |
|
|
|
//baseurl |
|
// const baseurl = 'http://39.106.78.171:8008'; |
|
|
|
@Injectable() |
|
export class BaseInterceptor implements HttpInterceptor { |
|
|
|
constructor(private http:HttpClient,private router:Router,private route:ActivatedRoute,public token:CacheTokenService,public snackBar: MatSnackBar,public isLogin: IsLoginService) {} |
|
|
|
intercept(req, next: HttpHandler) { |
|
|
|
let newReq = req.clone({ |
|
url: req.hadBaseurl ? `${req.url}` : `${req.url}`, |
|
}); |
|
if(!req.cancelToken) { |
|
/*获取token*/ |
|
let token = sessionStorage.getItem("token") || '' |
|
/*此处设置额外请求头,token令牌*/ |
|
newReq.headers = |
|
newReq.headers.set('Authorization', `Bearer ${token}`) |
|
} |
|
|
|
// 携带请求头发送下一次请求 |
|
return next.handle(newReq) |
|
.pipe( |
|
//箭头函数,注意this指向 |
|
catchError((err) => this.handleError(err)) |
|
) |
|
} |
|
|
|
// 捕获错误 |
|
//401 token过期 403没权限!!! 400参数错误 404未找到 614刷新令牌过期!!! |
|
|
|
private handleError(error: HttpErrorResponse) { |
|
// 用户认证失败返回登录页 |
|
if (error.status === 401||error.status === 614) { |
|
sessionStorage.clear() |
|
this.router.navigate(['/login']) |
|
const config = new MatSnackBarConfig(); |
|
config.verticalPosition = 'top'; |
|
config.duration = 3000 |
|
this.snackBar.open('用户认证信息过期,请重新登录','确定',config); |
|
} |
|
if (error.status === 403) { |
|
const config = new MatSnackBarConfig(); |
|
config.verticalPosition = 'top'; |
|
config.duration = 3000 |
|
this.snackBar.open('对不起,您无此权限','确定',config); |
|
} |
|
if (error.status === 400) { |
|
const config = new MatSnackBarConfig(); |
|
config.verticalPosition = 'top'; |
|
config.duration = 3000 |
|
this.snackBar.open('您输入的参数有误','确定',config); |
|
} |
|
|
|
if (error.error instanceof ErrorEvent) { |
|
// 发生客户端或网络错误。相应处理。 |
|
console.error('An error occurred:', error.error.message); |
|
} else { |
|
// 服务端返回http状态码 |
|
// 服务端返回错误信息 |
|
console.error( |
|
`Backend returned code ${error.status}, ` + |
|
`body was: ${error.error}`); |
|
} |
|
// 返回带有面向用户的错误信息 |
|
return throwError( |
|
error.error); |
|
}; |
|
}
|
|
|