angularjs封装$http为factory的方法
时间:2021-04-04 10:16:23|栏目:AngularJS|点击: 次
angularjs有本身封装的ajax服务$http,因为用惯了jQuery的ajax,所以,自己封装了一下angularjs的$http,代码如下
app.factory('dataFactory', function ($http, $q){ var factory = {}; factory.getlist = function(endpoint, method, headers, params) { var defer = $q.defer(); if (method == 'GET') { $http({ url: endpoint, method: "GET", headers: headers, params: params, }).success(function (data) { defer.resolve(data); }). error(function (data, status, headers, config) { // defer.resolve(data); defer.reject(data); }); } else { $http({ url: endpoint, method: method, headers: headers, data: params, }).success(function (data) { defer.resolve(data); }). error(function (data, status, headers, config) { // defer.resolve(data); defer.reject(data); }); } return defer.promise; }; return factory; });
在controller中引入dataFactory和$http即可使用更方便的调用ajax,一般情况下headers为
headers = {'Content-Type': 'application/json'};
params为一个json字符串
然后调用
dataFactory.getlist("/api/checkDuplicate", 'GET', headers, params).then(function(data) { //success函数 },function(data){ //error函数 })
但是其中又一次在项目中,后台框架使用的是Struts框架,在一个Python中使用的很好的dataFactory,在这里的后台取不到数,最后发现是应为header设置不对,而且params的格式也不正确,可以把header修改为
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
上面dataFactory中else添加转换params代码:
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; }; $http({ url: endpoint, method: method, headers: headers, data: param(params), }).success(function (data) { defer.resolve(data); }). error(function (data, status, headers, config) { // defer.resolve(data); defer.reject(data); });