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.
 
 
 
hai-oil-web/src/app/utils/Interceptor.service.ts

88 lines
2.7 KiB

import {Injectable} from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpHeaders
} from '@angular/common/http';
import {catchError, finalize} from 'rxjs/operators';
import {mergeMap} from 'rxjs/operators';
import {Observable} from 'rxjs';
import {USER_TOKEN} from "../data/login/localStorage.namespace";
import {BrowserStorageService} from "./localStorage.service";
import {Router} from "@angular/router";
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(
private router: Router, // 路由
private storage: BrowserStorageService,
) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let secureReq: HttpRequest<any>;
let modifiedHeaders: HttpHeaders;
const token = this.storage.get(USER_TOKEN);
if (token != null) {
modifiedHeaders =
req.headers.append('Cache-Control', 'no-cache')
.append('Pragma', 'no-cache')
.append('Authorization', token);
}
secureReq = req.clone({
url: req.url,
// @ts-ignore
headers: modifiedHeaders
});
// @ts-ignore
return next.handle(secureReq)
.pipe(
catchError((res: HttpResponse<any>) => {
let msg = '';
switch (res.status) {
case 401:
msg = '身份验证过期,请重新进入页面';
break;
case 200:
msg = '身份验证过期,请重新进入页面';
break;
case 404:
msg = '找不到地址';
break;
case 403:
msg = '业务错误';
break;
case 500:
msg = '服务器发生错误,请重试';
break;
}
this.jumpError(msg , res.status);
return Observable.create(res);
}),
finalize(() => {
}),
mergeMap(
// 有响应时成功;忽略其他事件
(event: any) => {
return Observable.create((observer: { next: (arg0: any) => any; }) => observer.next(event));
}),
);
}
jumpError(message: string , status: number) {
if (status == 401) {
this.router.navigateByUrl('/error/401').then(r => console.log("返回内容" ,r));
}
if (status == 403) {
this.router.navigateByUrl('/error/403').then(r => console.log("返回内容" ,r));
}
if (status == 404) {
this.router.navigateByUrl('/error/404').then(r => console.log("返回内容" ,r));
}
if (status == 500) {
this.router.navigateByUrl('/error/500').then(r => console.log("返回内容" ,r));
}
}
}