Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit dceafd3

Browse files
committed
feat($http): expose the defaults config as $http.defaults
Often it is impossible to set the http defaults during the config phase, because the config info is not available at this time. A good example is authentication - often the app needs to bootstrap, allow user to enter credentials and only then it gains access to session token which then should be sent to the server with every request. Without having the ability to set the defaults at runtime, the developer either has to resort to hacks, or has to set the session token header with every request made by the app.
1 parent 0a5050e commit dceafd3

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/ng/http.js

+16
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,9 @@ function $HttpProvider() {
223223
* with name equal to the lower-cased http method name, e.g.
224224
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
225225
*
226+
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
227+
* fassion as described above.
228+
*
226229
*
227230
* # Transforming Requests and Responses
228231
*
@@ -604,6 +607,19 @@ function $HttpProvider() {
604607
*/
605608
createShortMethodsWithData('post', 'put');
606609

610+
/**
611+
* @ngdoc property
612+
* @name angular.module.ng.$http#defaults
613+
* @propertyOf angular.module.ng.$http
614+
*
615+
* @description
616+
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
617+
* default headers as well as request and response transformations.
618+
*
619+
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
620+
*/
621+
$http.defaults = $config;
622+
607623

608624
return $http;
609625

test/ng/httpSpec.js

+16
Original file line numberDiff line numberDiff line change
@@ -940,6 +940,22 @@ describe('$http', function() {
940940
$httpBackend.flush();
941941
});
942942
});
943+
944+
945+
describe('defaults', function() {
946+
947+
it('should expose the defaults object at runtime', function() {
948+
expect($http.defaults).toBeDefined();
949+
950+
$http.defaults.headers.common.foo = 'bar';
951+
$httpBackend.expect('GET', '/url', undefined, function(headers) {
952+
return headers['foo'] == 'bar';
953+
}).respond('');
954+
955+
$http.get('/url');
956+
$httpBackend.flush();
957+
});
958+
});
943959
});
944960

945961

0 commit comments

Comments
 (0)