第八章有关于缓存的东西。
【通过$http交互】
传统的AJAX请求如下


1 var xmlhttp = new XMLHttpRequest(); 2 xmlhttp.onreadystatechange = function() { 3 if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { 4 var response = xmlhttp.responseText; 5 } else if (xmlhttp.status == 400) { // or really anything in the 4 series 6 // Handle error gracefully 7 } 8 }; 9 // Setup connection 10 xmlhttp.open(“GET”, “http://myserver/api”, true); 11 // Make the request 12 xmlhttp.send();
AngularJS Get请求如下,跟jQuery很相似


1 $http.get('api/user', {params: {id: '5'} 2 }).success(function(data, status, headers, config) { 3 // Do something successful. 4 }).error(function(data, status, headers, config) { 5 // Handle the error 6 });
AngularJS Post请求如下


1 var postData = {text: 'long blob of text'}; 2 // The next line gets appended to the URL as params 3 // so it would become a post request to /api/user?id=5 4 var config = {params: {id: '5'}}; 5 $http.post('api/user', postData, config 6 ).success(function(data, status, headers, config) { 7 // Do something successful 8 }).error(function(data, status, headers, config) { 9 // Handle the error 10 });
【定制你的http请求】
安哥拉提供了一个开箱即用的机制,一帮情况下足够了。但是如果你想:
添加一些授权消息头
改变请求的缓存状态
定制请求和响应
代码如下


1 $http({ 2 method: string, 3 url: string, 4 params: object, 5 data: string or object, 6 headers: object, 7 transformRequest: function transform(data, headersGetter) or 8 an array of functions, 9 transformResponse: function transform(data, headersGetter) or 10 an array of functions, 11 cache: boolean or Cache object, 12 timeout: number, 13 withCredentials: boolean 14 });
【设置http请求头】
AngularJS有默认的头:如下
1. Accept: application/json, text/plain, /
2. X-Requested-With: XMLHttpRequest
如果你想加新的。有两种方式:
第一种:修改默认的请求头


1 angular.module('MyApp',[]). 2 config(function($httpProvider) { 3 // Remove the default AngularJS X-Request-With header 4 delete $httpProvider.default.headers.common['X-Requested-With']; 5 // Set DO NOT TRACK for all Get requests 6 $httpProvider.default.headers.get['DNT'] = '1'; 7 });
第二种:修改某次请求头


1 $http.get('api/user', { 2 // Set the Authorization header. In an actual app, you would get the auth 3 // token from a service 4 headers: {'Authorization': 'Basic Qzsda231231'}, 5 params: {id: 5} 6 }).success(function() { // Handle success });
【缓存响应】
可以这样开启缓存


1 $http.get('http://server/myapi', { 2 cache: true 3 }).success(function() { // Handle success })
【请求与响应间的变化】