这篇文章主要介绍了angularjs如何封装$http为factory,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
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);
});
感谢你能够认真阅读完这篇文章,希望小编分享的“angularjs如何封装$http为factory”这篇文章对大家有帮助,同时也希望大家多多支持天达云,关注天达云行业资讯频道,更多相关知识等着你来学习!