Skip to content

Instantly share code, notes, and snippets.

@francoisblarel
Created March 18, 2014 11:24
Show Gist options
  • Select an option

  • Save francoisblarel/9618189 to your computer and use it in GitHub Desktop.

Select an option

Save francoisblarel/9618189 to your computer and use it in GitHub Desktop.
How to wrap angular $http for authentification. From the O'Reilly Book on AngularJS.
// This factory is only evaluated once, and authHttp is memorized. That is,
// future requests to authHttp service return the same instance of authHttp
servicesModule.factory('authHttp', function($http, Authentication) {
var authHttp = {};
// Append the right header to the request
var extendHeaders = function(config) {
config.headers = config.headers || {};
config.headers['Authorization'] = Authentication.getTokenType() +
' ' + Authentication.getAccessToken();
};
// Do this for each $http call
angular.forEach(['get', 'delete', 'head', 'jsonp'], function(name) {
authHttp[name] = function(url, config) {
config = config || {};
extendHeaders(config);
return $http[name](url, config);
};
});
angular.forEach(['post', 'put'], function(name) {
authHttp[name] = function(url, data, config) {
config = config || {};
extendHeaders(config);
return $http[name](url, data, config);
};
});
return authHttp;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment