AngularJS中轉換響應內容

Darren Ji發表於2016-01-27

 

從遠端API獲取到的響應內容,通常是json格式的,有時候需要對獲取到的內容進行轉換,比如去除某些不需要的欄位,給欄位取別名,等等。

本篇就來體驗在AngualrJS中如何實現。

在主頁面,還是從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>

 

以上,userName, url欄位是從源資料中轉換而來的,可能userName對應源資料中的fullName,可能源資料中有更多的欄位。

在AngularJS中,把module之間的關係梳理清楚是一種很好的習慣,比如按如下方式梳理:

 

angular.module('publicapi.controllers',[]);
angular.module('publicapi.services',[]);
angular.module('publicapi.transformers',[]);

angular.module('publicapi',[
    'publicapi.controllers',
    'publicapi.services',
    'publicapi.transformers'
])

 

資料還是從controller中來:

 

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

 

controller依賴於service.Api這個服務。

 

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

 

$http服務中的transformResponse欄位就是用來轉換資料來源的。services.Api依賴於services.transformer.ApiResponse這個服務,在這個服務力完成對資料來源的轉換。

 

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;
    };
});

 

以上,使用了underscore對資料來源進行map轉換。

 

相關文章