Angular http 拦截器

Angular http的拦截器一般用来处理每个http都需要添加的参数或者是统一处理错误信息

Angular1.x的http拦截器处理:

 $httpProvider.interceptors.push(function ($q) {
                return {
                    request: function (config) {

                        var url = config.url;

                        //这个token表示是在登录状态, 不要用在header中,options无法设置header
                        if(TASApp["x-auth-token"]){
                            if(url.indexOf("?") == -1){
                                url+="?x-auth-token="+TASApp["x-auth-token"];
                            }else{
                                url+="&x-auth-token="+TASApp["x-auth-token"];
                            }
                        }

                        config.url = url;

                        return config || $q.reject(config);
                    },

                    response: function (res) {
                        //统一处理返回信息,如果是错误则在这里统一处理,注意如果这样处理错误(reject),那么所有的错误信息会进入http的error回调,在success里默认就是成功,都可以不判断data.success
                        if (res.data.success == false) {
                            TASApp.ajaxReturnErrorHandler(res.data["info"]); //TASApp是一个constant对象
                            return $q.reject(res.data); //will go to error callback
                        } else if (res.data.success == "relogin") {
                            TASApp.relogin();
                            return $q.reject(res.data); //will go to error callback
                        } else {
                            return res; //will go to success callback
                        }
                    },

                    responseError: function (res) {
                                                //统一处理请求没发成功的错误
                        TASApp.ajaxErrorHandler();
                        return $q.reject(res);
                    }
                };
            });

Angular2.x的http拦截器处理:


export class AddHttpHeaderInterceptor implements HttpInterceptor {

    constructor(private formService: FormService, private formHelper: FormHelper, private message: NzMessageService, private lang: Lang) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

        // set  X-Requested-With that serve need to for ajax
        let clonedReq = req.clone({headers: req.headers.set(‘X-Requested-With‘, ‘XMLHttpRequest‘)});
        if (this.formService.currentUser) {
            //options http can not add x-auth-token, use param
            //clonedReq = req.clone({headers: req.headers.set(‘x-auth-token‘, this.formService.currentUser[‘x-auth-token‘])});

            //global add param x-auth-token and
            clonedReq = req.clone({params: req.params.set(‘x-auth-token‘, this.formService.currentUser[‘x-auth-token‘]),
                headers: req.headers.set(‘X-Requested-With‘, ‘XMLHttpRequest‘)});
        }

        // ===========================================================
        // global handle error
        // ===========================================================
        return next.handle(clonedReq).pipe(
            catchError(this.formService.handleError),
            //handle success false
            filter(res => {
            if(res[‘statusText‘] && res[‘statusText‘] === ‘OK‘){
                if(res[‘body‘] && (res[‘body‘][‘success‘] == false || res[‘body‘][‘success‘]==‘relogin‘)){
                    if(res[‘body‘][‘success‘] == ‘relogin‘){
                        //handle relogin here, can add some message
                        (<any>window).location.href = this.formHelper.getBaseUrl()+‘login‘;
                        return false;
                    } else {
                        //if no info will have a code
                        this.message.error(res[‘body‘][‘info‘] || this.lang.lang["errorCode"][res[‘body‘][‘code‘]]);
                        console.log(res);
                        //if return false will not trigger subscribe function, if you need trigger return true
                        return true;

                        /*
                        this will fire subscribe error handle, that means if backend error will go to subscribe->error,
                        subscribe->next is only handle backend success, bug if services use like MyShares/getFormInfo that will have problem,
                        need add error handle for every http request and run handler function
                        this.http.get(url).subscribe(obj=>{handle when backend success},error=>{handle when backend error}
                        */
                        //throw new Error("error");
                    }
                }
            }
            return true;
        })
        );
    }
}

@NgModule({
    declarations: [

    ],
    imports: [

    ],
    providers: [
        {provide: HTTP_INTERCEPTORS, useClass: AddHttpHeaderInterceptor, deps: [FormService, FormHelper, NzMessageService, Lang], multi: true},
        {provide: APP_INITIALIZER, useFactory: loginAndInitForm, deps: [FormService], multi: true},
        {provide: NZ_I18N, useValue: zh_CN},
        {provide: NZ_MODAL_CONFIG, useValue: {autoBodyPadding: true}},
        {provide: NZ_MESSAGE_CONFIG, useValue: {nzDuration: 3000}}
    ],
    bootstrap: [AppComponent]
})

原文地址:https://blog.51cto.com/13934921/2467421

时间: 2024-07-31 17:05:02

Angular http 拦截器的相关文章

angular 拦截器

介绍:$http service在Angular中用于简化与后台的交互过程,其本质上使用XMLHttpRequest或JSONP进行与后台的数据交互.在与后台的交互过程中,可能会对每条请求发送到Server之前进行预处理(如加入token),或者是在Server返回数据到达客户端还未被处理之前进行预处理(如将非JSON格式数据进行转换):当然还有可能对在请求和响应过程过发生的问题进行捕获处理.所有这些需求在开发中都非常常见,所以Angular为我们提供了$http拦截器,用来实现上述需求. An

angular之interceptors拦截器

<!DOCTYPE html> <html ng-app="nickApp"> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title&g

ionic之angular拦截器

ionic作为应用,肯定和服务器有数据交换,分散处理api太繁琐,所以一般用拦截器来集中处理. 主要由以下几个方面的应用: 服务器地址注入 错误处理 token注入 日志处理 无token时跳转至登录页面 ... 有四个方法 request: function(config) requestError: function(config) response: function(response) responseError: function(response) 基本看方法名称就知道其意义.具体的

(转)Angular中的拦截器Interceptor

什么是拦截器? 异步操作 例子 Session 注入(请求拦截器) 时间戳(请求和响应拦截器) 请求恢复 (请求异常拦截) Session 恢复 (响应异常拦截器) 转之:http://my.oschina.net/ilivebox/blog/290881?p=1 原文:Interceptors in AngularJS and Useful Examples $httpAngularJS 的 $http 服务允许我们通过发送 HTTP 请求方式与后台进行通信.在某些情况下,我们希望可以俘获所有

angular http interceptors 拦截器使用分享

拦截器 在开始创建拦截器之前,一定要了解 $q和延期承诺api 出于全局错误处理,身份验证或请求的任何同步或异步预处理或响应的后处理目的,希望能够在将请求移交给服务器之前拦截请求,并在将请求移交给服务器之前将响应拦截发起这些请求的应用程序代码-拦截器利用promise api满足同步和异步预处理的需求. 拦截器是$httpProvider通过将它们添加到$httpProvider.interceptors数组而向其注册的服务工厂.调用工厂并注入依赖项(如果指定),并返回拦截器. 有两种拦截器(和

关于angularJs的拦截器的使用

拦截器,在JavaScript中就是拦截http请求.它不仅可以拦截request,还可以拦截response. 拦截request是为了在请求发送前设置一些配置,比如在header中添加一些信息.如果每个请求都要添加一些配置数据,就可以使用request拦截.拦截response是为了在获得服务器返回的数据后,ajax处理数据前先对数据做一些处理,这样就不需要在每一次ajax中处理了,减少代码量. 具体的看下面的例子: angular.module('demo') //this service

AngularJs HTTP响应拦截器实现登陆、权限校验

$httpAngularJS 的 $http 服务允许我们通过发送 HTTP 请求方式与后台进行通信.在某些情况下,我们希望可以俘获所有的请求,并且在将其发送到服务端之前进行操作.还有一些情况是,我们希望俘获响应,并且在完成完成调用之前处理它.一个很好例子就是处理全局 http 异常.拦截器(Interceptors)应运而生.本文将介绍 AngularJS 的拦截器,并且给几个有用的例子. 什么是拦截器? $httpProvider 中有一个 interceptors 数组,而所谓拦截器只是一

AngularJS 拦截器和应用例子(转)

$httpAngularJS 的 $http 服务允许我们通过发送 HTTP 请求方式与后台进行通信.在某些情况下,我们希望可以俘获所有的请求,并且在将其发送到服务端之前进行操作.还有一些情况是,我们希望俘获响应,并且在完成完成调用之前处理它.一个很好例子就是处理全局 http 异常.拦截器(Interceptors)应运而生.本文将介绍 AngularJS 的拦截器,并且给几个有用的例子. 什么是拦截器? $httpProvider 中有一个 interceptors 数组,而所谓拦截器只是一

AngularJS 拦截器

在需要进行身份验证时,在请求发送给服务器之前或者从服务器返回时对其进行拦截,是比较好的实现手段. 例如,对于身份验证,如果服务器返回401状态码,将用户重定向到登录页面. AngularJS通过拦截器提供了一个从全局层面对响应进行处理的途径. 拦截器是$http服务的基础中间件,用来向应用的业务流程中注入新的逻辑. 一共有四种拦截器,两种成功,两种失败. request AngularJS通过$http设置对象来对请求拦截器进行调用. response requestError response