真正的應用幾乎都得跟伺服器打交道。行動應用與新興的 Chrome 桌面應用或許是少數例外,但除此之外,不論你是想把資料存到雲端,還是要讓使用者之間即時互動,都繞不開這一步。
AngularJS 為此提供了 $http 服務,它提供了一組可擴充的抽象方法,讓伺服器互動變得容易:支援 HTTP、JSONP 與 CORS,內建防禦 JSON 脆弱性與 XSRF 的安全性機制,能輕鬆轉換請求與回應資料,甚至還實作了簡單的快取。
以下用一個購物站為例:把商品資料從伺服器抓回來,取代原本寫在記憶體裡的假資料。後端怎麼寫不在本文範圍內,就當作我們已經有個服務,請求 /products 時會回傳一段 JSON 格式的商品清單。
回應長得像這樣:
[
{
"id": 0,
"title": "Paint pots",
"description": "Pots full of paint",
"price": 3.95
},
{
"id": 1,
"title": "Polka dots",
"description": "Dots with that polka groove",
"price": 12.95
},
{
"id": 2,
"title": "Pebbles",
"description": "Just little rocks, really",
"price": 6.95
}
...etc...
]
function ShoppingController($scope, $http) {
$http.get('/products').success(function (data, status, headers, config) {
$scope.items = data;
});
}
模板中這樣使用:
<body ng-controller="ShoppingController">
<h1>Shop!</h1>
<table>
<tr ng-repeat="item in items">
<td>{{item.title}}</td>
<td>{{item.description}}</td>
<td>{{item.price | currency}}</td>
</tr>
</table>
</body>
長期來看,讓一個「服務」去代理與伺服器的互動會更有利,因為這個服務可以被多個控制器共用,不必在每個 controller 裡重複寫一遍 $http.get。例如:
angular.module('shop').factory('Products', function ($http) {
return {
all: function () {
return $http.get('/products');
}
};
});
function ShoppingController($scope, Products) {
Products.all().then(function (res) {
$scope.items = res.data;
});
}
此外,新版的 AngularJS 已改用 then 搭配 success / error 回呼的寫法;若你手上是新版本專案,請以 then 為準。