リモート API から取得される応答内容は通常 json 形式であるため、不要なフィールドを削除したり、フィールドにエイリアスを付与したりするなど、取得した内容を変換する必要がある場合があります。
この記事では、AngualrJS での実装方法を体験してみましょう。
メイン ページで、引き続きコントローラーからデータを取得します。
1 2 3 4 5 6 7 8 | <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 では、モジュール間の関係を次のように整理するのが良い習慣です。
1 2 3 4 5 6 7 8 | angular.module( 'publicapi.controllers' ,[]);
angular.module( 'publicapi.services' ,[]);
angular.module( 'publicapi.transformers' ,[]);
angular.module( 'publicapi' ,[
'publicapi.controllers' ,
'publicapi.services' ,
'publicapi.transformers'
])
|
ログイン後にコピー
データは引き続きコントローラーから取得されます:
1 2 3 4 | angular.module( 'publicapi.controllers' )
.controller( 'controllers.View' ,[ '$scope' , 'service.Api' , function ( $scope , api){
$scope .repos = api.getUserRepos( "" );
}]);
|
ログイン後にコピー
コントローラーはservice.Apiサービスに依存します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 サービスに依存します。
1 2 3 4 5 6 7 8 9 10 11 | 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;
};
});
|
ログイン後にコピー
上では、データ ソースのマッピングにアンダースコアが使用されています。