Home > Web Front-end > JS Tutorial > AngularJS transform response content_AngularJS

AngularJS transform response content_AngularJS

WBOY
Release: 2016-05-16 15:17:41
Original
1356 people have browsed it

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> 
Copy after login

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'
]) 
Copy after login

The data still comes from the controller:

angular.module('publicapi.controllers')
.controller('controllers.View',['$scope', 'service.Api', function($scope, api){
$scope.repos = api.getUserRepos("");
}]); 
Copy after login

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;
}
};
}]) 
Copy after login

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;
};
}); 
Copy after login

Above, underscore is used to map the data source.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template