配餐项目前端文件
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.

85 lines
2.1 KiB

2 years ago
import { Inject, Injectable } from "@angular/core";
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpResponse,
} from "@angular/common/http";
import { catchError, Observable, switchMap, tap, throwError, timer } from "rxjs";
import { Router } from "@angular/router";
import { NzMessageService } from "ng-zorro-antd/message";
import { ResponseType } from "@cdk/types";
@Injectable({ providedIn: "root" })
export class HTTPInterceptor implements HttpInterceptor {
constructor(private router: Router, private msg: NzMessageService) {}
private msgFlag = false;
private localStroageKey = "catering";
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem(this.localStroageKey);
if (token) {
req = req.clone({
// headers: req.headers.set('Authorization', `Bearer ${token}`),
headers: req.headers.set("Authorization", token),
});
}
return this.handleResult(next, req);
}
private handleResult(next: HttpHandler, authReq: HttpRequest<any>): Observable<HttpEvent<any>> {
return next.handle(authReq).pipe(
tap((res) => {
if (res instanceof HttpResponse) {
const Authorization = res.headers.get("Authorization");
if (Authorization) {
localStorage.setItem(this.localStroageKey, Authorization);
}
// if (this.decConfig.triggerError) {
// this.decConfig.triggerError(res);
// }
if (res.body?.success === false && res.body.desc) {
throw new HttpErrorResponse({ error: res.body });
}
}
}),
catchError((err: HttpErrorResponse) => {
const throwErr = throwError(() => err);
if (this.msgFlag) {
return throwErr;
}
setTimeout(() => {
this.msgFlag = false;
}, 1500);
const error: ResponseType = err.error;
this.msgFlag = true;
if (error.success === false) {
this.msg.error(error.desc);
switch (error.code) {
case 401:
this.router.navigate(["/", "login"]);
break;
default:
break;
}
} else {
this.msg.error("服务器出错了!");
}
return throwErr;
})
);
}
}