AngularJS conversion response content, angularjs conversion response
The response content obtained from a remote API is usually in json format. Sometimes, you need to convert the obtained content, such as removing unnecessary fields and alias the fields.
This article describes how to implement AngualrJS.
Take data from the controller on the home page.
<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 the userName corresponds to the fullName in the source data, and there are more fields in the energy data.
In AngularJS, it is a good habit to sort out the relationship between modules clearly, for example, sort them 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 is still from the controller:
angular.module('publicapi.controllers').controller('controllers.View',['$scope', 'service.Api', function($scope, api){$scope.repos = api.getUserRepos("");}]);
The 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;}};}])
In the $ http service, the transformResponse field is used to convert the data source. Services. Api relies on services. transformer. ApiResponse, which converts data sources.
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;};});
The preceding figure uses underscore to map the data source.
Articles you may be interested in:
- Analysis on AngularJs HTTP Response interceptor
- Quick learning of AngularJs HTTP Response interceptor