AngularJS Intercept all $http JSON responses
You can intercept responses by adding an interceptor to $httpProvider.interceptors
with Angular 1.1.4+ (see documentation here search for interceptors).
For a specific content type like json you can potentially reject changes or throw an exception even if the call was a success. You can modify the response.data
that will get passed to your controller code as well here:
myModule.factory('myHttpInterceptor', function ($q) {
return {
response: function (response) {
// do something on success
if(response.headers()['content-type'] === "application/json; charset=utf-8"){
// Validate response, if not ok reject
var data = examineJSONResponse(response); // assumes this function is available
if(!data)
return $q.reject(response);
}
return response;
},
responseError: function (response) {
// do something on error
return $q.reject(response);
}
};
});
myModule.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
NOTE: Here is the original answer for versions prior to 1.1.4 (responseInterceptors
were deprecated with Angular 1.1.4):
Maybe there's a better way but I think you can do something similar to this post with the http response interceptor (described here) (for a specific content type like json) where you potentially reject changes or throw an exception even though the call was a success. You can modify the response.data
that will get passed to your controller code as well here.
myModule.factory('myHttpInterceptor', function ($q) {
return function (promise) {
return promise.then(function (response) {
// do something on success
if(response.headers()['content-type'] === "application/json; charset=utf-8"){
// Validate response if not ok reject
var data = examineJSONResponse(response); // assumes this function is available
if(!data)
return $q.reject(response);
}
return response;
}, function (response) {
// do something on error
return $q.reject(response);
});
};
});
myModule.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('myHttpInterceptor');
});
Another solution is to create a service and use that around the $http variable.
angular.module('App', [])
.factory('myHttp',['$http',function($http) {
return function(url, success, failure) {
$http.get(url).success(function(json) {
var data = examineJSONResponse(json);
data && data.success ? success() : failure();
}).error(failure);
);
}
}]);
And now this can be called like:
myHttp(url, onSuccess, onFailure);