Created
May 8, 2015 10:43
-
-
Save nitso/c6c8fa9ea8519139ef6b to your computer and use it in GitHub Desktop.
Angular $http init: json error interceptor + POST processor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
var jsonErrorInterceptor = function($q) { | |
return function(promise) { | |
// error handler | |
var triggerError = function(message) { | |
if (message instanceof Array) { | |
message = message[0]; | |
} | |
console.log(message); | |
}; | |
// reject when json field 'error' exists | |
var success = function(response) { | |
if (response.data.error || response.data.parseError) { | |
triggerError(response.data.error || response.data.parseError); | |
return $q.reject(response); | |
} | |
return response; | |
} | |
// reject on ajax errors | |
var error = functin(response) { | |
triggerError('Ошибка при выполнении запроса'); | |
return $q.reject(response); | |
} | |
return promise.then(success, error); | |
} | |
}; | |
var initAngular = function(module, params) { | |
params = params || function() {}; | |
var module = angular.module(module, params); | |
module.config(function($provide, $httpProvider) { | |
$httpProvider.responseInterceptors.push(MO.Angular.jsonErrorInterceptor); | |
// correct POST header | |
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; | |
// transform request data | |
$httpProvider.defaults.transformRequest = function(data, headers) { | |
if (!data) { | |
return ''; | |
} | |
// using jQuery to serialize request data | |
// without jQuery check http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object | |
data = $.param(data); | |
return data; | |
}; | |
}); | |
return module; | |
}; | |
// usage: | |
// var myModule = initAngular('myModule', []); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment