Angularjs encapsulates $ http as the factory method, angularjsfactory
Angularjs has its own encapsulated ajax service $ http. Because it is used to jQuery's ajax, it encapsulates angularjs's $ http by itself. The Code is as follows:
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; });
Introduce dataFactory and $ http in the controller to call ajax more conveniently. Generally, headers is
headers = {'Content-Type': 'application/json'};
Params is a json string.
Then call
DataFactory. getlist ("/api/checkDuplicate", 'get', headers, params ). then (function (data) {// success function}, function (data) {// error function })
However, once again in the project, the backend framework uses the Struts framework. dataFactory, which is used in a Python project, cannot be retrieved in the backend, finally, we found that the header should be set incorrectly and the params format is incorrect. You can change the header
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
In dataFactory, add the params conversion code for else:
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); });
I personally think this method is more convenient, and I want to record it. I hope it will help you learn it, and I hope you can support the house of helping customers a lot.