Skip to content

Instantly share code, notes, and snippets.

@petebacondarwin
Created December 15, 2014 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petebacondarwin/ebc0b2c3c40151787f0b to your computer and use it in GitHub Desktop.
Save petebacondarwin/ebc0b2c3c40151787f0b to your computer and use it in GitHub Desktop.
Suggested extendable $http configuration...
angular.module('resources', [])
// So we create a new service for each configuration of $http that we want
.factory('myServerAPI', function($http) {
function customRequestTransform(value) { ... }
function customResponseTransform(value) { ... }
// Provide a configuration object that corresponds to our specific $http needs
// for this particular service
var config = {
// Provide or override the standard config properties from default
url: 'https://api.my-server.com',
headers: {
common: { ... }
},
transformRequest: [customeRequestTransform],
transformResponse: [customResponseTransform],
cache: null,
timeout: 10000,
// But also override the interceptors for this too!
interceptors: ['customHttpInterceptor']
};
// We use some function such as extend to create a "new" instance of $http that is
// configured as we want it
return $http.extend(config);
})
// Even more powerful this new custom $http service exposes an `extend` method too
// So we can further customize our services on a more fine grained level while keeping
// shared config in a reasonble place
.factory('userAPI', function(myServerAPI) {
var config = {
// By providing a relative URL we can use the base URL from the myServerAPI config
url: 'auth/user'
// It reuses the config from myServerAPI by default but we can override bits
headers: angular.extend(myServerAPI, { get: ... })
};
return myServerAPI.extend(config);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment