Skip to content

Instantly share code, notes, and snippets.

@lukehorvat
Last active December 23, 2015 02:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukehorvat/6569072 to your computer and use it in GitHub Desktop.
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.
.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