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

首頁 > 開發 > JS > 正文

AngularJS轉換響應內容

2024-05-06 16:27:55
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了AngularJS轉換響應內容 的相關資料,需要的朋友可以參考下
 

從遠程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轉換。



注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铁力市| 巨鹿县| 佛教| 治多县| 车险| 仙游县| 遂平县| 江川县| 北海市| 锦州市| 郁南县| 涿州市| 新昌县| 宣汉县| 崇明县| 策勒县| 内乡县| 河池市| 枣阳市| 琼结县| 兴仁县| 汕头市| 海阳市| 新泰市| 龙井市| 天祝| 龙南县| 论坛| 西吉县| 象州县| 栖霞市| 儋州市| 满城县| 项城市| 东乌| 丰城市| 昆山市| 涡阳县| 洪江市| 南溪县| 增城市|