Folks,
我在用$http.get
and $http.post
遍布我的代码。我对如何以全局方式处理这些调用期间发生的错误感到有点迷失。
目前我有.success(doSomething).error(doSomething)
每次通话时。
我想更改此设置,而只是在页面顶部显示错误。
我读到有关使用拦截器的内容myapp.something
。但我完全不明白如何实现这一点。
请协助
响应拦截器是在 angularjs 应用程序的配置阶段附加的。您可以使用它们来全局响应任何 $http 请求。请注意,模板文件也使用 $http 请求,因此您可能希望将拦截器中的某些请求过滤为仅您希望响应的请求。
很好地理解了promises http://docs.angularjs.org/api/ng.%24q成功使用响应拦截器需要模式。
以下是如何使用它们的示例:
angular.module('services')
.config(function($httpProvider){
//Here we're adding our interceptor.
$httpProvider.responseInterceptors.push('globalInterceptor');
})
//Here we define our interceptor
.factory('globalInterceptor', function($q){
//When the interceptor runs, it is passed a promise object
return function(promise){
//In an interceptor, we return another promise created by the .then function.
return promise.then(function(response){
//Do your code here if the response was successful
//Always be sure to return a response for your application code to react to as well
return response;
}, function(response){
//Do your error handling code here if the response was unsuccessful
//Be sure to return a reject if you cannot recover from the error somehow.
//This way, the consumer of the $http request will know its an error as well
return $q.reject(response);
});
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)