Created
March 18, 2014 11:24
-
-
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 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
| // 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