12bet,可以使用内置的$http服务直接同外部进行通信。$http服务只是简单的封装了浏览器原生的XMLHttpRequest对象。
$http服务返回一个promise对象,具有success
和error
两个方法。如果响应状态码在200和299之间,会认为响应成功,12bet,调用success回调,否则调用error回调
$http({
method: 'GET',
url: '/api/users.json'
}).success(function(data, status, headers, config) {
// 当相应准备就绪时调用
}).error(function(data, status, headers, config) {
// 当响应以错误状态返回时调用
});
$http服务提供了一些顺手的快捷方法供我们使用,12bet,这些方法简化了复杂设置:
12博体育,将$http当作函数来调用时,需要传入一个设置对象,用来说明如何构造XHR对象:
默认情况下,CORS请求不会发送cookie,而withCredentials标记会在请求中加入
Access-Control-Allow-Credentials
头,这样请求就会将目标域的cookie包含在请求中
传给then()
方法的响应对象包含:
默认情况下,$http服务不会对请求进行本地缓存。在发送单独的请求时,我们可以通过向$http请求传入一个布尔值或者一个缓存实例来启用缓存
通过
cache: true
启用缓存,默认会使用$cacheFactory
这个服务
可以通过$cacheFactory来建立LRU的缓存:
var lru = $cacheFactory('lru', {
capacity: 20
});
// $http请求
$http.get('/api/users.json', {
cache: lru
})
.success(function(data) {})
.error(function(data) {});
通过$httpProvider能够在.config()中给所有$http请求设置一个默认的缓存:
angular.module('myApp', [])
.config(function($httpProvider, $cacheFactory) {
$httpProvider.defaults.cache = $cacheFactory('lru', {
capacity: 20
});
});
可以通过拦截器从全局层面对响应进行处理。拦截器的核心是服务工厂,通过向$httpProvider. interceptors数组中添加服务工厂,在$httpProvider中进行注册。
一共有四种拦截器:
通过.factory()
创建拦截器,并在.config()
中,使用$httpProvider.interceptors.push()
添加拦截器
angular.module('myApp', [])
.factory('myInterceptor', function($q) {
var interceptor = {
'request': function(config) {
return config;
},
'response': function(response) {
return response;
},
'requestError': function(rejection) {
return rejection;
// return $q.reject(rejection);
},
'responseError': function(rejection) {
return rejection;
// return $q.reject(rejection);
}
};
return interceptor;
});
angular.module('myApp', [])
.config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');//添加拦截器
});
使用.config()
可以向所有请求中添加特定的HTTP头,默认的请求头保存在$httpProvider.defaults.headers.common
对象中,可以对其修改或扩充:
angular.module('myApp', [])
.config(function($httpProvider) {
$httpProvider.defaults.headers
.common['X-Requested-By'] = 'MyAngularApp';
});
在运行时通过$http对象的defaults属性也可以修改这些默认值:
$http.defaults.common['X-Auth'] = 'RandomString';
如果仅需要对特定方法进行修改,如修改POST方法,可以这样:
angular.module('myApp', [])
.config(function($httpProvider) {
$httpProvider.defaults.headers
.post['X-Posted-By'] = 'MyAngularApp';
});
//或者这样
angular.module('myApp', []).config(function($httpProvider) {
$httpProvider.defaults.headers
.post['X-Posted-By'] = 'MyAngularApp';
});