任何时候,如果我们想要为请求添加全局功能,例如身份认证、错误处理等,在请求发送给服务器之前或服务器返回时对其进行拦截,是比较好的实现手段。

angularJs通过拦截器提供了一个从全局层面进行处理的途径。

四种拦截器

实现 request 方法拦截请求

request: function(config) {
// do something on request success
return config || $q.when(config);
} 

该方法会在 $http 发送请求后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configuration object)作为参数,然后必须返回配置对象或者 promise 。如果返回无效的配置对象或者 promise 则会被拒绝,导致 $http 调用失败。

实现 requestError 方法拦截请求异常

requestError: function(rejection) {
  // do something on request error  return $q.reject(rejection);
} 

有时候一个请求发送失败或者被拦截器拒绝了,请求异常拦截器会俘获那些被上一个请求拦截器中断的请求。它可以用来恢复请求或者有时可以用来撤销请求之前所做的配置,比如说关闭进度条,激活按钮和输入框什么之类的。

实现 response 方法拦截响应

response: function(response) {
  // do something on response success
return response || $q.when(response);} 

该方法会在 $http 接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(response object)作为参数,然后必须返回响应对象或者 promise。响应对象包括了请求配置(request configuration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者 promise 会被拒绝,导致$http 调用失败。

实现 responseError 方法拦截响应异常

responseError: function(rejection) {
// do something on response error  return $q.reject(rejection);
} 

有时候我们后台调用失败了,也有可能它被一个请求拦截器拒绝了或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用。

拦截器核心

拦截服务工厂

var app = angular.module("ajaxHttp", []);
app.factory("httpInterceptor", [ "$q", "$rootScope", function($q, $rootScope) {
return {
request: function(config) {
// do something on request success
return config || $q.when(config);
},
   requestError: function(rejection) {
     // do something on request error
     return $q.reject(rejection)
   },
response: function(response) {
// do something on response success
return response || $q.when(response);
},
responseError : function(rejection) {
// do something on response error
return $q.reject(rejection);
}
};
}]); 

注册拦截工厂方法

app.config(["$httpProvider", function($httpProvider) {
  $httpProvider.interceptors.push("httpInterceptor");
}]); 

示例

对401,404的拦截处理

app.config(["$httpProvider", function($httpProvider) { 
$httpProvider.interceptors.push('httpInterceptor'); 
}]); 
app.factory("httpInterceptor", ["$q", "$injector", function($q, $injector) {
return {
"responseError": function(response) {
if (response.status == 401) {
var rootScope = $injector.get('$rootScope');
var state = $injector.get('$rootScope').$state.current.name;
rootScope.stateBeforLogin = state;
rootScope.$state.go("login");
return $q.reject(response);
}
else if (response.status === 404) {
console.log("404!");
return $q.reject(response);
}
}
};
]);

以上内容给大家分享快速学习AngularJs HTTP响应拦截器 的相关知识,希望大家喜欢,同时感谢大家一直以来对网站的支持。

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。