$httpProvider中的interceptor拦截器,$http的jsonp服务等http相关知识点

interceptor

factory服务定义拦截器,配置$httpProvider将刚注册的服务push进$httpProvider.interceptors,这个的感觉和node中间件相似。拦截器会在不同http阶段执行不同的操作,具体例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
angular.module('myApp').controller('myCtrl',function($http){
$http.get('http://localhost:8004').success(function (data,status,headers,config) {
console.log(arguments)
}).error(function () {
console.log(arguments)
}).then(function (response) {
console.log(response)
})
});
angular.module('myApp').factory('myinterceptor',function () {
return{
'request':function (config) {
console.log('1request');
return config;
},
'response':function (response) {
console.log('2response');
return response;
},
'requestError':function (rejection) {
console.log('3requestError');
},
'responseError':function (rejection) {
console.log('4responseError');
}
}
});
angular.module('myApp').config(function ($httpProvider) {
$httpProvider.interceptors.push('myinterceptor');
})

自定义的拦截器里返回的对象有四个属性,分别是在不同的阶段执行的:

  • request:http请求发送之前,参数是http的配置对象,这边一定要return配置对象
  • response:http请求返回之前(相当于success之前),参数是返回的对象(返回的data、状态码等),也要return这个对象
  • requestError:请求发送失败或者被拦截器拒绝时调用,参数是错误对象
  • responseError:后台响应失败时调用,参数是错误对象(状态码等都有)

jsonp

$http服务提供了jsonp的方法,调用百度搜索的接口,cb回调show这个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
angular.module('myApp').directive('keyword',function ($http,$window) {
return{
link:function (scope, element, attrs) {
scope.$watch(attrs['ngModel'],function () {
if(scope.data||''){
$http.jsonp('http://suggestion.baidu.com/su?wd='+scope.data+'&cb=show');
}
});
$window.show = function (data) {
scope.items = data.s;
}
}
}
})