angular的$http服務

來源:互聯網
上載者:User



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];    }  };});





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.