当前位置:AngularJS API / ng / 服务(service) / $http
$http$http是Angular的一个核心服务,它有利于浏览器通过XMLHttpRequest 对象或者 JSONP和远程HTTP服务器交互。
$HTTP API 是基于 $q服务暴露的deferred/promise APIs。
快捷使用方式:
设置HTTP请求头:
$HTTP服务将会给所有请求自动创建HTTP头。这个默认设置能完全的通过访问$httpProvider.defaults.headers配置对象配置。目前包含默认配置:
$httpProvider.defaults.headers.common
//-- Accept:application/json,text/plain
$httpProvider.defaults.headers.post
//-- Content-Type:application/json
$httpProvider.defaults.headers.put
//-- Content-Type:application/json
添加或覆盖这些默认值
添加或删除这些配置对象的属性。
全局配置:
$httpProvider.defaults.headers.post = {“my-header”:”value”}
单请求配置:
$http({
method:”POST”,
url:”url”,
headers:{
“Content-Type”:” // your config”
},
data:{ data: ” // your data” }
})
重写每个请求的默认转换。
下面的代码演示添加一个新的响应转换,在运行后的默认响应转换。
Function appendTransform(defaults,transform){
defaults:angular.isArray(defaults)?defaults:[defaults];
return defaults.concat(transform);
}
$http({
url:”url”,
method:”GET”,
transformResponse:appendTransform($http.defaults.transformResponse,function(){
return doTransform(value);
})
})
设置http请求缓存。
$http.defaults.cache = true/false;
请求拦截
angular.module(“xxx”,[])
.config([“$httpProvider”,function($httpProvider){
$httpProvider.interceptors.push(“yourInterceptors”);
}])
.factory(“yourInterceptors”,[“$q”,”dependency”, function($q,dependency){
return {
“request”:function(config){
// do something on success
return config;
},
“requestError”:function(rejection){
// do something on error
If(canRecover(rejection)){
return responseOrNewPromise
}
return $q.reject(rejection);
},
“response”:function(response){
// do something on success
return response;
},
“responseError”:function(rejection){
// do something on error
If(canRecover(rejection)){
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
}]);
$httpBackend
$cacheFactory
$rootScope
$q
$injector
$http(config);
| 参数 | 类型 | 描述 |
|---|---|---|
| config | object |
|
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| data | * |
请求内容。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| data | * |
请求内容。 |
| config | object |
请求配置对象。 |
| 参数 | 类型 | 描述 |
|---|---|---|
| url | string |
请求地址。 |
| data | * |
请求内容。 |
| config | object |
请求配置对象。 |
当前正在等待的请求的配置对象数组。主要是为了用于调试目的。
请求头配置默认属性。
$httpParamSerializerJQLike
Http参数序列化程序。序列化程序也将按字母顺序排序的参数。
<div ng-controller="FetchController">
<select ng-model="method" aria-label="Request method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80" aria-label="URL" />
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || 'Request failed';
$scope.status = response.status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
Hello, $http!
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});