mirror of
https://github.com/Hopiu/angular.js.git
synced 2026-03-30 04:50:28 +00:00
feat($http): add response interceptors
This commit is contained in:
parent
dbd880cc0a
commit
188bdf7768
2 changed files with 51 additions and 0 deletions
|
|
@ -81,6 +81,8 @@ function $HttpProvider() {
|
|||
}
|
||||
};
|
||||
|
||||
var responseInterceptors = this.responseInterceptors = [];
|
||||
|
||||
this.$get = ['$httpBackend', '$browser', '$exceptionHandler', '$cacheFactory', '$rootScope', '$q',
|
||||
function($httpBackend, $browser, $exceptionHandler, $cacheFactory, $rootScope, $q) {
|
||||
|
||||
|
|
@ -129,6 +131,10 @@ function $HttpProvider() {
|
|||
deferredResp = $q.defer(),
|
||||
promise = deferredResp.promise;
|
||||
|
||||
forEach(responseInterceptors, function(interceptor) {
|
||||
promise = interceptor(promise);
|
||||
});
|
||||
|
||||
promise.success = function(fn) {
|
||||
promise.then(function(response) {
|
||||
fn(response.data, response.status, response.headers, config);
|
||||
|
|
|
|||
|
|
@ -31,6 +31,51 @@ describe('$http', function() {
|
|||
}));
|
||||
|
||||
|
||||
describe('$httpProvider', function() {
|
||||
|
||||
describe('interceptors', function() {
|
||||
|
||||
it('should default to an empty array', inject(function($httpProvider) {
|
||||
expect($httpProvider.responseInterceptors).toEqual([]);
|
||||
}));
|
||||
|
||||
|
||||
it('should pass the responses through interceptors', inject(function($httpProvider, $q) {
|
||||
// just change the response data and pass the response object along
|
||||
$httpProvider.responseInterceptors.push(function(httpPromise) {
|
||||
return httpPromise.then(function(response) {
|
||||
response.data += '!';
|
||||
return response;
|
||||
});
|
||||
});
|
||||
|
||||
// return a new resolved promise representing modified response object
|
||||
$httpProvider.responseInterceptors.push(function(httpPromise) {
|
||||
return httpPromise.then(function(response) {
|
||||
var deferred = $q.defer();
|
||||
deferred.resolve({
|
||||
data: response.data + '?',
|
||||
status: 209,
|
||||
headers: response.headers,
|
||||
config: response.config
|
||||
});
|
||||
return deferred.promise;
|
||||
});
|
||||
});
|
||||
}, function($http, $httpBackend) {
|
||||
$httpBackend.expect('GET', '/foo').respond(201, 'Hello');
|
||||
$http.get('/foo').success(function(data, status) {
|
||||
expect(data).toBe('Hello!?');
|
||||
expect(status).toBe(209);
|
||||
callback();
|
||||
})
|
||||
$httpBackend.flush();
|
||||
expect(callback).toHaveBeenCalledOnce();
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it('should do basic request', function() {
|
||||
$httpBackend.expect('GET', '/url').respond('');
|
||||
$http({url: '/url', method: 'GET'});
|
||||
|
|
|
|||
Loading…
Reference in a new issue