Angular拦截器
把token带入在每次请求过程中,并判断是否登录超时,就需要angular拦截器,把每次返回的请求给拦截处理,比如:登录超时,跳转到登录界面,重新登录。
新建ts文件http.interceptors.ts
import {getToken, removeCookieUserInfo, removeToken} from '../../utils/auth';
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable, of, throwError} from 'rxjs';
import {catchError, map, retry, tap} from 'rxjs/operators';
import {NzMessageService} from 'ng-zorro-antd/message';
import {Router} from '@angular/router';
@Injectable()
export class HttpInterceptors implements HttpInterceptor{
constructor(private http: HttpClient, private message: NzMessageService, private router: Router) {}
index = 0;
intercept(req, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Authorization', getToken() ? getToken() : 'noAuth')
});
// send cloned request with header to the next handler.
return next.handle(authReq).pipe( /*retry为失败重试次数,可自由设置*/
retry(0), tap(res => {
if (res instanceof HttpResponse){
if (res.body.status === 401){
if (this.index === 0){
removeToken();
removeCookieUserInfo();
this.message.error('请重新登录');
}
this.index++;
this.router.navigate(['/login']);
}
}
}),
/*捕获响应错误,可根据需要自行改写,我偷懒了,直接用的官方的*/
catchError(err => {
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}
并在app.module.ts中注入拦截器
providers: [{ provide: NZ_I18N, useValue: zh_CN }, CookieService,
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptors, multi: true }, ],