1. 建立一个 class类HttpRequestInterceptor,实现 HttpInterceptor重写 intercept,代码如下
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {Router} from '@angular/router';
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.endsWith('login')) {
return next.handle(req).pipe(tap(event => {
if (event instanceof HttpResponse) {
}
}, e => {
if (e.status === 401) {
alert('用户名或密码错误');
}
}));
}
const modifiedReq = req.clone({
// 在header中添加token
setHeaders: {Authorization: 'Bearer ' + localStorage.getItem('access_token')}
});
const _this = this;
return next.handle(modifiedReq).pipe(tap(event => {
if (event instanceof HttpResponse) {
console.log(event);
}
}, e => {
console.log(e);
if (e.status === 401) {
_this.router.navigateByUrl('/login');
}
}));
}
}
2. 在 app.module.ts的providers添加
{provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true}