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中添加tokensetHeaders: {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}
如果觉得《angular中使用拦截器处理http请求》对你有帮助,请点赞、收藏,并留下你的观点哦!