angular统一拦截器的书写
2019-07-11 本文已影响0人
海染蓝了天_2d47
统一拦截器,顾名思义就是统一拦截所有的请求,然后根据请求书写自己的业务逻辑,比如请求结果session过期处理,在header头部加上验证参数token等等,这个时候就需要用到拦截器。
首先我们创建一个类,名为AuthHttpInterceptor的拦截器并且继承了HttpInterceptor拦截器:
image.png
拦截器的具体实现部分:
image.png
业务处理:一些通用操作,根据服务器返回来的状态处理不同的业务,请求的参数不对,token过期没有通过验证,这个时候需要我们做统一处理
image.png
最后我们要在app.module.ts中添加我们的拦截器
image.png
已经写了好几年现在需要用到,重新整理了一下,记得点赞哦
代码如下:
import { Injectable } from "@angular/core";
import {
HttpErrorResponse,
HttpEvent,
HttpHandler, HttpHeaderResponse, HttpInterceptor, HttpRequest, HttpResponse,
} from "@angular/common/http";
import { Observable, of } from "rxjs/index";
import { catchError, mergeMap } from "rxjs/internal/operators";
import { StorageService } from '../servers/storage.service';
/**
- 统一拦截器
*/
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
headers: any;
constructor(
private storageService: StorageService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpHeaderResponse | HttpResponse<any>> {
let req: any;
if (request.url.endsWith('/login')) {
let req = request.clone({
headers: request.headers.set('JSESSIONID', 'JSESSIONID ' + null)
});//这里可以在请求中加参数
return this.newMethod(next, req)
} else {
let req = request.clone({
headers: request.headers.set('Content-Type','application/x-www-form-urlencoded')
});
return this.newMethod(next, req)
}
}
private newMethod(next: HttpHandler, req: HttpRequest<any>): Observable<HttpHeaderResponse | HttpResponse<any>> {
return next.handle(req).pipe(mergeMap((event: any) => {
// 正常返回,处理具体返回参数
if (event instanceof HttpResponse && event.status === 200) {
//console.log(event);
return this.handleData(event); //具体处理请求返回数据
}
return of(event);
}), catchError((err: HttpErrorResponse) => this.handleData(err)));
}
private handleData(event: HttpResponse<any> | HttpErrorResponse): Observable<any> {
// 业务处理:一些通用操作
switch (event.status) {
case 200:
if (event instanceof HttpResponse) {
//const body: any = event.body;
return of(event);
}
break;
case 401: // 未登录状态码
case 404:
case 500:
default:
return of(event);
}
}
//
private getAccessToken(): string {
const token = this.storageService.get('AccessToken')
return token;
}
private getSessionId(): string {
const token = this.storageService.get('jsessionid')
return token;
}
}