Last active
December 23, 2015 02:49
-
-
Save lukehorvat/6569072 to your computer and use it in GitHub Desktop.
An example of how to use request/response interceptors in AngularJS 1.2 for consistent API interactions. This code does two things: 1) Automatic injection of the user auth token in all API requests. 2) Automatic event firing when the user receives an API response indicating a 401 (unauthorised) request.
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
.config ($httpProvider) -> | |
$httpProvider.interceptors.push ($q, $rootScope, apiUrl, authToken) -> | |
request: (config) -> | |
# Intercept API requests and inject the auth token. | |
config.headers["X-Auth-Token"] = authToken if config.url.indexOf(apiUrl) is 0 and authToken? | |
config or $q.when config | |
responseError: (response) -> | |
# Intercept unauthorised API responses and fire an event. | |
$rootScope.$broadcast "unauthorisedApiRequest" if response.config.url.indexOf(apiUrl) is 0 and response.status is 401 | |
$q.reject response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment