Home >Web Front-end >JS Tutorial >AngularJS transform response content_AngularJS
The response content obtained from the remote API is usually in json format. Sometimes it is necessary to convert the obtained content, such as removing some unnecessary fields, giving aliases to fields, etc.
In this article, let’s experience how to implement it in AngualrJS.
On the main page, still get data from the controller.
<body ng-app="publicapi"> <ul ng-controller="controllers.View"> <li ng-repeat="repo in repos"> <b ng-bind="repo.userName"></b> <span ng-bind="repo.url"></span> </li> </ul> </body>
Above, the userName and url fields are converted from the source data. Maybe userName corresponds to the fullName in the source data, and maybe there are more fields in the source data.
In AngularJS, it is a good habit to sort out the relationship between modules. For example, sort it out as follows:
angular.module('publicapi.controllers',[]); angular.module('publicapi.services',[]); angular.module('publicapi.transformers',[]); angular.module('publicapi',[ 'publicapi.controllers', 'publicapi.services', 'publicapi.transformers' ])
The data still comes from the controller:
angular.module('publicapi.controllers') .controller('controllers.View',['$scope', 'service.Api', function($scope, api){ $scope.repos = api.getUserRepos(""); }]);
Controller depends on the service.Api service.
angular.module('publicapi.services').factory('services.Api',['$q', '$http', 'services.transformer.ApiResponse', function($q, $http, apiResponseTransformer){ return { getUserRepos: function(login){ var deferred = $q.defer(); $http({ method: "GET", url: "" + login + "/repos", transformResponse: apiResponseTransformer }) .success(function(data){ deferred.resolve(data); }) return deferred.promise; } }; }])
The transformResponse field in the $http service is used to transform the data source. services.Api depends on the services.transformer.ApiResponse service, which completes the conversion of the data source.
angular.module('publicapi.transformers').factory('services.transformer.ApiResponse', function(){ return function(data){ data = JSON.parse(data); if(data.length){ data = _.map(data, function(repo){ return {userName: reop.full_name, url: git_url}; }) } return data; }; });
Above, underscore is used to map the data source.