/* * @Createdby: Microsoft Visual Code * @Author: ferried * @Email: harlancui@outlook.com * @LastEditors: ferried * @Version: 1.0.0-SNAPSHOT * @Description: none * @Date: 2019-03-11 08:48:53 * @LastEditTime: 2019-03-18 11:53:13 */ import {Injector, Injectable, Inject} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {catchError} from 'rxjs/operators'; import {NzMessageService, NzModalService} from 'ng-zorro-antd'; import { HttpInterceptor, HttpClient, HttpResponseBase, HttpErrorResponse, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import {Router} from '@angular/router'; import {ConfigService, UserService} from "@yunzai/stars"; const CODEMESSAGE = { 200: '服务器成功返回请求的数据。', 201: '新建或修改数据成功。', 202: '一个请求已经进入后台排队(异步任务)。', 204: '删除数据成功。', 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。', 401: '用户没有权限(令牌、用户名、密码错误),请备份填写信息后,刷新页面以重新登录。', 403: '用户得到授权,但是访问是被禁止的。', 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。', 406: '请求的格式不可得。', 410: '请求的资源被永久删除,且不会再得到的。', 422: '当创建一个对象时,发生一个验证错误。', 500: '服务器发生错误,请检查服务器。', 502: '网关错误。', 503: '服务不可用,服务器暂时过载或维护。', 504: '网关超时。', }; @Injectable() export class DefaultInterceptor implements HttpInterceptor { constructor(private injector: Injector, private userService: UserService, private configService: ConfigService) { } get http(): HttpClient { return this.injector.get(HttpClient); } get msg(): NzMessageService { return this.injector.get(NzMessageService); } get confirmMsg(): NzModalService { return this.injector.get(NzModalService); } get router(): Router { return this.injector.get(Router); } handleData(ev: HttpResponseBase): Observable { switch (ev.status) { case 200: break; case 401: this.confirmMsg.error({ nzTitle: '

401

', nzContent: '用户没有权限(令牌、用户名、密码错误),请重新登录!', nzKeyboard: false, nzOnOk: () => { this.confirmMsg.closeAll(); // this.userService.logout(); window.location.href = `${this.configService.config.gateway}/${this.configService.config.cas}/app/logout`; } }); return; break; case 403: case 404: case 406: case 410: case 422: case 502: case 503: case 504: // 跳转到错误页 this.router.navigate(['/<%=project%>/error', ev.status]); return throwError(ev); case 400: case 500: case 600: // 弹出错误提示 this.msg.error(`${(ev as any).error.message}`); return throwError(ev); default: if (ev instanceof HttpErrorResponse) { this.msg.error(`HTTP${ev.status}: ${ev.statusText} ${ev.url}`); return throwError(ev); } break; } return of(ev); } intercept(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe( // mergeMap((event: any) => { // if (event instanceof HttpResponseBase) { // return this.handleData(event); // } // return of(event); // }), catchError((err: HttpErrorResponse) => this.handleData(err)), ); } }