ufwxwa
Last Updated: August 31, 2016
·
3.887K
· otupman
45975fcc42c585f7ddd9711e1f5198a7

AngularJS and $http - transform the request *and* the response

Occasionally you might wish to pre-process requests or responses that go out/come into Angular before the standard Angular processing gets to them.

For example, perhaps you decide to use Binary JSON rather than pure JSON (no, no clue why). To achieve this you can modify $httpProvider.defaults.transformResponse and $httpProvider.defaults.transformRequest. They're arrays, so you can add in a series of transformers, if you wish.

myModule.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.transformResponse = function(data) {
      return performSomeTransformation(data);
    };
  }])

Your transformed data will then be passed on to your $http handler in nice object form (assuming that's what you wanted). You could, if you were strange, just pass back the received data without converting to JSON.