Created
September 23, 2013 21:04
-
-
Save mustmodify/6676952 to your computer and use it in GitHub Desktop.
APINotices is an AngularJS module that displays a "working" and "error" div during AJAX requests.
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
angular.module('ApiNotice', []). | |
config(function ($httpProvider) | |
{ | |
$httpProvider.responseInterceptors.push('myHttpInterceptor'); | |
var spinnerFunction = function (data, headersGetter) | |
{ | |
// todo start the spinner here | |
$('#api-error').hide(); | |
$('#api-access').show(); | |
return data; | |
}; | |
$httpProvider.defaults.transformRequest.push(spinnerFunction); | |
}). | |
// register the interceptor as a service, intercepts ALL angular ajax http calls | |
factory('myHttpInterceptor', function ($q, $window) { | |
return function (promise) { | |
return promise.then(function (response) { | |
// do something on success | |
// todo hide the spinner | |
$('#api-access').hide(); | |
return response; | |
}, function (response) { | |
window.resp = response; | |
if( response.status == 422 ) | |
{ | |
$('#api-error .message').html('Errors:'); | |
errors = []; | |
if( window.resp.data && window.resp.data.errors ) | |
{ | |
errors = window.resp.data.errors; | |
} | |
else if( window.resp.data ) | |
{ | |
errors = window.resp.data; | |
} | |
$.each(errors, function(a, b) { $('#api-error .message').append("<li>" + a + " " + b + "</li>");}); | |
} | |
// do something on error | |
// todo hide the spinner | |
$('#api-access').hide(); | |
$('#api-error').show(); | |
return $q.reject(response); | |
}); | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment