服务的参数格式化
原来post请求格式, 传参使用不方便
$http({
url:"post.php",
method:"post",
data:"name=sk&age=666"
});
考虑把json对象参数格式转化,成formDate形式
想要传入格式:
$http({
url:"post.php",
method:"post",
formData:{
name:sk
age:666
}
});
所以自定义服务, 将传入的json格式 转成formData格式:name=sk&age=666
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body ng-app="app" ng-controller="skController">
</body>
<script src="angular.js"></script>
<script>
//1.创建模块
var app = angular.module('app', []);
//2.创建控制器
app.controller('skController', ['$scope','$http' ,'formData', 'formData2', 'formDataService', function ($scope, $http,formData,formData2, formDataService ) {
var params = {
name:'sk',
age:666
};
$http({
url:"post.php",
method:"post",
//开始格式
//data:"name=sk&age=666"
//factory 方式一:
//data:formData(params)
//factory 方式二:
//data:formData2.dataPost(params)
//service 方式三:
data:formDataService.form(params)
});
}]);
//3.绑定模块 ng-app='app'
//4.绑定控制器
/**
把对象格式转化成formDate形式
{
name:sk
age:666
}
最终结果格式:
name=sk&age=666
想要传入格式:
formData({
name:sk
age:666
})
*/
//自定义服务目的: 把公用的功能, 给封装到一起,进行复用
//1.factory 方式一
app.factory('formData', function () {
return function (obj) {
var res = "";
for (key in obj){
//name=sk&age=666&
res += key + "=" + obj[key] + "&";
}
res = res.slice(0, -1);
console.log(res);
return res;
}
});
//2.factory 方式二
app.factory('formData2', function () {
function formDataPost(obj) {
var res = "";
for (key in obj){
//name=sk&age=666&
res += key + "=" + obj[key] + "&";
}
res = res.slice(0, -1);
console.log(res);
return res;
}
return{
dataPost: formDataPost
}
});
//3.service
app.service('formDataService', function () {
this.form = function (obj) {
var res = "";
for (key in obj){
//name=sk&age=666&
res += key + "=" + obj[key] + "&";
}
res = res.slice(0, -1);
console.log(res);
return res;
}
})
</script>
</html>