为angular强化Http请求
我先说问题,代码下面一起给出
添加patch
前两天了解到除了get、post、put还有一个叫patch的相对较新的提交方法,主要是用来做局部更新的意思。
但是angular没有这个方法。
改变请求的格式
angular在提交中文内容是会有乱码出现的情况,编码解码也不行,如果用过zepto的同学可能也遇到过这样的问题。结果导致无法提交服务端想要的信息。
增加请求拦截
对于请求的成功和失败进行拦截操作,比如对401做跳转登录页面的操作。
下面是代码
.config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; //增加拦截服务 $httpProvider.interceptors.push('userStateInterceptor'); //增加patch请求方法 $httpProvider.defaults.headers.patch = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' } /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function (obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } return query.length ? query.substr(0, query.length - 1) : query; }; // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function (data) { return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; }]).service("userStateInterceptor", ['$location','$q', function ($location,$q) { //定义拦截操作 var interceptor = { 'request': function (config) { return config; }, 'response': function (response) { return response; }, 'requestError': function (rejection) { return $q.reject(response); }, 'responseError': function (response) { //这里做401的拦截 switch (response.status) { case 401: $location.path('login'); break; } return $q.reject(response); } } return interceptor; }]);