第八章有关于缓存的东西。

【通过$http交互】

传统的AJAX请求如下

 var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
} else if (xmlhttp.status == 400) { // or really anything in the 4 series
// Handle error gracefully
}
};
// Setup connection
xmlhttp.open(“GET”, “http://myserver/api”, true);
// Make the request
xmlhttp.send();

AngularJS Get请求如下,跟jQuery很相似

 $http.get('api/user', {params: {id: '5'}
}).success(function(data, status, headers, config) {
// Do something successful.
}).error(function(data, status, headers, config) {
// Handle the error
});

AngularJS Post请求如下

 var postData = {text: 'long blob of text'};
// The next line gets appended to the URL as params
// so it would become a post request to /api/user?id=5
var config = {params: {id: '5'}};
$http.post('api/user', postData, config
).success(function(data, status, headers, config) {
// Do something successful
}).error(function(data, status, headers, config) {
// Handle the error
});

【定制你的http请求】

安哥拉提供了一个开箱即用的机制,一帮情况下足够了。但是如果你想:

  添加一些授权消息头

  改变请求的缓存状态

  定制请求和响应

代码如下

 $http({
method: string,
url: string,
params: object,
data: string or object,
headers: object,
transformRequest: function transform(data, headersGetter) or
an array of functions,
transformResponse: function transform(data, headersGetter) or
an array of functions,
cache: boolean or Cache object,
timeout: number,
withCredentials: boolean
});

【设置http请求头】

AngularJS有默认的头:如下

1. Accept: application/json, text/plain, /
2. X-Requested-With: XMLHttpRequest

如果你想加新的。有两种方式:

第一种:修改默认的请求头

 angular.module('MyApp',[]).
config(function($httpProvider) {
// Remove the default AngularJS X-Request-With header
delete $httpProvider.default.headers.common['X-Requested-With'];
// Set DO NOT TRACK for all Get requests
$httpProvider.default.headers.get['DNT'] = '1';
});

第二种:修改某次请求头

 $http.get('api/user', {
// Set the Authorization header. In an actual app, you would get the auth
// token from a service
headers: {'Authorization': 'Basic Qzsda231231'},
params: {id: 5}
}).success(function() { // Handle success });

【缓存响应】

可以这样开启缓存

 $http.get('http://server/myapi', {
cache: true
}).success(function() { // Handle success })

【请求与响应间的变化】

05-28 08:20