Angular http 拦截器的使用方法
admin
2023-02-12 20:00:06
0

这篇文章给大家分享的是有关Angular http 拦截器的使用方法。小编觉得挺实用的,因此分享给大家学习。如下资料是关于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, 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
                        (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]
})

以上就是Angular http 拦截器的使用方法介绍,详细使用情况还得要大家自己使用过才能知道具体要领。如果想阅读更多相关内容的文章,欢迎关注行业资讯频道!


相关内容

热门资讯

中国海警局新闻发言人就菲位南海... 中国海警局新闻发言人姜略表示,7月24日,菲律宾组织7艘公务船、3艘海警舰、1艘运鱼船,并唆使大量渔...
外交部回应美国对数十国加征关税 7月24日,外交部发言人林剑主持例行记者会。有记者问:美国新一轮关税措施将于今天生效,外交部能否就此...
台湾岛以东相关海域治理进入经济... 为全面了解我国管辖海域渔业资源状况,7月17日至23日,农业农村部中国水产科学研究院东海水产研究所,...
日本正式决定设立国家情报局:系... 据凤凰卫视报道,日本政府7月24日正式决定设立国家情报局,计划于31日召开首次国家情报会议。这是日本...
伍斌任福建省副省长 据“新福建”客户端消息,7月24日,福建省十四届人大常委会第二十三次会议闭幕。会议表决通过了有关人事...
滚筒洗衣机脱水转不起来 滚筒洗衣机脱水转不起来:1、洗衣机顶盖的安全开关损坏。洗衣机在脱水的过程属于高速运作的机械运动。在脱...
洗衣机甩干桶嗡嗡响转不起来 洗衣机甩干桶嗡嗡响转不起来1、可能是洗衣机甩干桶下面的相关轴承长时间使用,缺乏润滑油导致的。2、可能...
不平衡滚筒洗衣机脱水转不起来 不平衡滚筒洗衣机脱水转不起来洗衣机不脱水时,首先检查洗衣机内是否有水。如果有水,首先打开排水阀检查里...
洗衣机脱水桶转不起来 1、有可能是因为洗衣机的内筒当中所放置的衣物过多了导致的。2、还有可能是因为电压不正常导致的。3、也...
西门子洗衣机滚筒转不起来 西门子洗衣机滚筒转不起来可能是以下几种原因:电压过低,导致滚筒洗衣机转不动;洗涤的物品太多会导致滚筒...