Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.
.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
You can’t perform that action at this time.