angular的$http服务

来源:互联网 发布:开源的推荐系统算法库 编辑:程序博客网 时间:2024/05/21 09:41



Usage
$http(config);



Arguments


config

Object describing the request to be made and how it should be processed. The object has following properties:

  • method – {string} – HTTP method (e.g. 'GET', 'POST', etc)
  • url – {string|TrustedObject} – Absolute or relative URL of the resource that is being requested; or an object created by a call to $sce.trustAsResourceUrl(url).
  • params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
  • data – {string|Object} – Data to be sent as the request message data.


example:

var req = { method: 'POST', url: 'http://example.com', headers: {   'Content-Type': undefined }, data: { test: 'test' }}$http(req).then(function(){...}, function(){...});


摘自angular1.x官网:https://docs.angularjs.org/api/ng/service/$http



其中设置对象可以包含以下主要的键:

①method

可以是:GET/DELETE/HEAD/JSONP/POST/PUT

②url:绝对的或者相对的请求目标
③params(字符串map或者对象)
这个键的值是一个字符串map或对象,会被转换成查询字符串追加在URL后面。如果值不是字符串,会被JSON序列化。

?

④data(字符串或者对象)

这个对象中包含了将会被当作消息体发送给服务器的数据。通常在发送POST请求时使用。

从AngularJS 1.3开始,它还可以在POST请求里发送二进制数据。要发送一个blob对象,你可以简单地通过使用data参数来传递它。

?


在控制器中使用$http

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.resizeColumns', 'ui.grid.moveColumns']); app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {  $scope.gridOptions = {    enableSorting: true,    columnDefs: [      { field: 'name', minWidth: 200, width: 250, enableColumnResizing: false },      { field: 'gender', width: '30%', maxWidth: 200, minWidth: 70 },      { field: 'company', width: '20%' }    ]  };   $http.get('/data/100.json')    .success(function(data) {      $scope.gridOptions.data = data;    });}]);

摘自angular ui grid: http://ui-grid.info/docs/#/tutorial/204_column_resizing



获得数据并对数据进行过滤

  $http.get('/data/100.json')    .success(function(data) {      data.forEach( function setGender( row, index ){        row.gender = row.gender==='male' ? '1' : '2';      });       $scope.gridOptions.data = data;    });}]).filter('mapGender', function() {  var genderHash = {    1: 'male',    2: 'female'  };   return function(input) {    if (!input){      return '';    } else {      return genderHash[input];    }  };});





原创粉丝点击