失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > angular中使用拦截器处理http请求

angular中使用拦截器处理http请求

时间:2019-05-26 09:29:50

相关推荐

angular中使用拦截器处理http请求

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请求》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。