问题
Folks,
I am using $http.get
and $http.post
all over my code. I am kind of lost as to how to handle errors that occur during these calls in a global fashion.
Currently I have .success(doSomething).error(doSomething)
on every call.
I would like to change this and instead simply display the error on top of my page.
I read about using interceptors with myapp.something
. But I absolutely do not understand how to implement this.
Kindly assist
回答1:
Response interceptors are attached during the config phase of an angularjs app. You can use them to globally respond to any $http request. Be aware, template files also use $http request, so you may wish to filter some requests in your interceptor to only the ones you wish to respond to.
A good understanding of the promises pattern is needed to successfully use response interceptors.
Heres an example of how they are used:
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);
});
}
});
来源:https://stackoverflow.com/questions/17687804/handling-http-get-and-http-post-errors-in-angularjs