Transformation functions
Transforamtion functions are used to format the data before sending the request to the server and after recieveing the response from the server. Let's suppose that you are using two different Servces in your Application and the data is coming in the format given below.
Although the data from both the Services is similar and represents the same piece of information but only the property names are different. To sort out this data in your Application is difficult and may be a mess in your Application code. Transformation functions provide a solution to this problem by reading the data from each Service and transforming it into one data format.
After transformation, the propertis are standarized and you can easily manipulate the data. Angular provides default transformation for the request and response and they can be accessed through $http.default object.
Transform Response
Syntax
- $http({
- url: '',
- method: 'GET',
- transformResponse: function(data, headersGetter,status) {
-
-
-
-
-
- return transformedObject;
- }
-
- }).then(function(response) {
-
- }).catch(function(){
-
- });
Plunker -
Transformation Response Function Example
Transform Request
Syntax
- $http.post('url', data, {
- transformRequest: function(data, headersGetter) {
-
-
- return JSON.stringify(data);
- }
- });
Plunker - Transformation Request Function Example
Interceptors
Interceptors are used to modify $http configuration objects before the request is sent to the Server and the response object before they are handed over to the application. They are implemented as Service factory and can be used by adding them into $httpProvider.interceptors array.
Syntax
- var myApp = angular.module('myApp', [])
-
- .factory('myInterceptor', ['$q', '$log', function($q, $log) {
-
- return {
-
- request: function(config) {
-
- return config;
- },
- responseError: function(response) {
-
- return response;
- }
-
- }
-
- }]);
-
-
- myApp.config(['$httpProvider', function($httpProvider) {
-
- $httpProvider.interceptors.push('myInterceptor');
-
- }]);
Plunker - Interceptors Example
Summary
In this blog, we saw how can we transform the request before sending it to the Server and the response after receiving from the Server, using AngularJS Transformation functions and how we can modify $http configuration object through Interceptors.