龙空技术网

angular5-http拦截器实现

CoderTan 116

前言:

如今大家对“http拦截”大约比较关怀,朋友们都需要了解一些“http拦截”的相关内容。那么小编也在网摘上搜集了一些对于“http拦截””的相关内容,希望兄弟们能喜欢,同学们快快来学习一下吧!

前沿:

在ng项目开发中,时常会需要拦截http请求,在ng2-4项目开发中,我都是借助的github上开源的封装好的拦截器:angular2-interceptors;

前端时间开发ng5的版本的项目,就自己实现了一下http拦截器;

即实现angular暴露的HttpInterceptor接口即可;

代码:

代码如下:http-interceptor.ts

import { Injectable } from '@angular/core';import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpHeaders, HttpErrorResponse } from '@angular/common/http';import { Observable } from 'rxjs/Observable';import 'rxjs/add/observable/throw';import 'rxjs/add/operator/catch';import 'rxjs/add/operator/do';@Injectable()export class MyHttpInterceptor implements HttpInterceptor {constructor() { }intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {// 拦截请求前:在此处可以处理请求头;例如Content-type// 此处也可以加loading的监听// 我这里是有2个不同的服务器地址let headerOptions = { 'Content-Type': 'application/json;charset=UTF-8' };if(req.url.indexOf('upload/bytes') > -1) {headerOptions = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'};}let reqOptions = {headers: new HttpHeaders(headerOptions),withCredentials: true};const authReq = req.clone(reqOptions);//发送新请求头的http请求return next.handle(authReq).do((event: HttpEvent<any>) => { //HttpResponseif(event instanceof HttpResponse){//拦截请求后:响应成功//成功loading结束}},(err: any) => { //HttpErrorResponseif(err instanceof HttpErrorResponse){//拦截请求后:错误处理//err loading结束return Observable.throw(err);}})}}
使用:

在app.module.ts中的providers(提供商)中加入如下代码即可:

{provide: HTTP_INTERCEPTORS,useClass: MyHttpInterceptor, // 导入我们自己实现的MyHttpInterceptormulti: true},
代码截图

代码

添加到供应商

标签: #http拦截 #http请求拦截工具