网络编程 发布日期:2024/11/6 浏览次数:1
在angularJs中增加了一个对全局的http请求统一做出处理的api--interceptors
Interceptors 有两个处理时机,分别是:
其引用场景包括
使用实例如下:
commonService.config(['$httpProvider',function($httpProvider){ //$httpProvider.defaults.headers.common = {'X-Auth-Token': $.cookie('x_auth_token'),'Content-Type':'application/json;charset=UTF-8'}; //添加拦截器; $httpProvider.interceptors.push(function ($q) { return { request: function (obj) { $('.loading').show(); obj.headers['X-Auth-Token'] = $.cookie('x_auth_token'); if(!obj.headers['Content-Type']) obj.headers['Content-Type'] = 'application/json;charset=UTF-8'; var url, params,method; //加盟店请求 mylog('jiamengdian::',sessionStorage.getItem("chainStorefrnId")); if(sessionStorage.getItem("chainStorefrnId")){ //增加操作人id,name和storeid等信息 //操作人姓名 var operatorName = $.cookie("userType") == "employee" "username")) : decodeURI($.cookie("frnName")); //操作人id var operatorId = $.cookie("userId"); //加盟店id var operatorStoreId = $.cookie("frnId"); if (obj.method) { method = obj.method.toLowerCase(); } else { method = "get"; } //处理url,区分首次授信还是追加授信 var flag_url = sessionStorage.getItem('chainStoreFlag'); mylog('flag_url',flag_url); if(flag_url && flag_url == "firstcredit"){ //提交需要加上加盟店标识 if(obj.url.indexOf("firstcredit/createPerFirstCredit")!=-1){ //标识个人提交 obj.url = obj.url.replace('firstcredit/createPerFirstCredit','firstcredit/perFirstCreditByFranchisee'); } else if(obj.url.indexOf("firstcredit/createBusiFirstCredit")!=-1){ //标识企业提交 obj.url = obj.url.replace('firstcredit/createBusiFirstCredit','firstcredit/createBusiFirstCreditByFranchisee'); } } else { url = obj.url + "" + operatorName + "&operatorId=" + operatorId + "&operatorStoreId=" + operatorStoreId; } } return obj; }, response: function (res) { $(".loading").hide(); return res; }, responseError: function (err) { $(".loading").hide(); return $q.reject(err); } }; }); }]);
改api共有4个方法,分别为request ,requestError ,response ,responseError ,这个四个方法非必选,可根据需要调用,前两个是请求的前置处理,后两个是针对请求的响应的处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。