Angularjs encapsulates $ http as the factory method, angularjsfactory

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.