The response content obtained from the remote API, usually in JSON format, sometimes needs to be converted to the retrieved content, such as removing some unwanted fields, alias The fields, and so on.
This article will experience how to achieve in Angualrjs.
In the main page, or from the controller to get the data.
<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>
Above, UserName, URL fields are converted from the source data, possibly userName the corresponding source data in the FullName, there are more fields in the energy data.
In Angularjs, it is a good practice to sort out the relationships between the module, such as by combing the following ways:
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 coming 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 for this 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. The API relies on the Services.transformer.ApiResponse service, where the Service force completes the transformation 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, a map transformation of the data source is made using the underscore.