国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

AngularJS轉(zhuǎn)換響應(yīng)內(nèi)容

2019-11-20 10:40:40
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

從遠(yuǎn)程API獲取到的響應(yīng)內(nèi)容,通常是json格式的,有時(shí)候需要對(duì)獲取到的內(nèi)容進(jìn)行轉(zhuǎn)換,比如去除某些不需要的字段,給字段取別名,等等。

本篇就來(lái)體驗(yàn)在AngualrJS中如何實(shí)現(xiàn)。

在主頁(yè)面,還是從controller中拿數(shù)據(jù)。

<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字段是從源數(shù)據(jù)中轉(zhuǎn)換而來(lái)的,可能userName對(duì)應(yīng)源數(shù)據(jù)中的fullName,可能源數(shù)據(jù)中有更多的字段。

在AngularJS中,把module之間的關(guān)系梳理清楚是一種很好的習(xí)慣,比如按如下方式梳理:

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

數(shù)據(jù)還是從controller中來(lái):

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

controller依賴于service.Api這個(gè)服務(wù)。

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服務(wù)中的transformResponse字段就是用來(lái)轉(zhuǎn)換數(shù)據(jù)源的。services.Api依賴于services.transformer.ApiResponse這個(gè)服務(wù),在這個(gè)服務(wù)力完成對(duì)數(shù)據(jù)源的轉(zhuǎn)換。

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對(duì)數(shù)據(jù)源進(jìn)行map轉(zhuǎn)換。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜昌市| 神池县| 沽源县| 镇远县| 甘洛县| 调兵山市| 祥云县| 宁乡县| 方山县| 桃园县| 西丰县| 乌兰浩特市| 梁山县| 西丰县| 登封市| 杭州市| 南京市| 桐乡市| 油尖旺区| 苏尼特右旗| 安丘市| 深州市| 桦甸市| 天全县| 梓潼县| 富民县| 万载县| 南部县| 马边| 安西县| 河津市| 东兰县| 宣武区| 鹰潭市| 长治市| 江达县| 锦屏县| 达孜县| 礼泉县| 富平县| 隆安县|