AngularJS从URL获取多数组JSON数据方法咨询
处理嵌套多数组的JSON数据获取(AngularJS)
嘿,作为AngularJS新手,碰到这种嵌套了多层数组的JSON确实容易犯懵,我来一步步帮你拆解怎么获取数据~
首先,先理清楚你给的JSON结构:
{
"Details": [
{ "approved": [{...}] },
{ "pending": [{...}] },
{ "rejected": [{...}] },
{ "resubmit": [{...}] }
]
}
简单说,返回的顶层对象里有个Details数组,数组里的每一项分别对应一个分类(approved、pending等),每个分类里又存着具体的数据数组。
第一步:用$http服务发起请求
AngularJS里我们常用$http服务来请求远程数据,记得在控制器里注入这个服务哦。
第二步:提取目标数据
这里有两种方式,一种是依赖Details数组的顺序(适合后端返回结构固定的情况),另一种是遍历匹配属性名(更健壮,不怕顺序变化)。
基础版(依赖数组索引)
如果确定后端返回的Details数组顺序不会变,直接通过索引提取即可:
angular.module('myApp', []) .controller('DataController', ['$http', function($http) { var vm = this; // 替换成你的实际API地址 $http.get('your-data-url') .then(function(response) { // 先拿到顶层的Details数组 const details = response.data.Details; // 从Details的对应索引中提取各个分类的数组 vm.approvedList = details[0].approved; vm.pendingList = details[1].pending; vm.rejectedList = details[2].rejected; vm.resubmitList = details[3].resubmit; }) .catch(function(error) { console.log('数据请求失败:', error); }); }]);
健壮版(不依赖顺序)
如果担心后端调整Details里的元素顺序,可以遍历数组匹配属性名,这样更稳妥:
angular.module('myApp', []) .controller('DataController', ['$http', function($http) { var vm = this; $http.get('your-data-url') .then(function(response) { const details = response.data.Details; // 遍历Details数组,匹配每个分类的属性 details.forEach(category => { if (category.approved) vm.approvedList = category.approved; else if (category.pending) vm.pendingList = category.pending; else if (category.rejected) vm.rejectedList = category.rejected; else if (category.resubmit) vm.resubmitList = category.resubmit; }); }) .catch(function(error) { console.log('数据请求失败:', error); }); }]);
第三步:在视图中展示数据
拿到数据后,用ng-repeat指令就能轻松渲染列表啦,顺便处理一下可能的null值,避免页面显示奇怪的内容:
<div ng-app="myApp" ng-controller="DataController as ctrl"> <h3>已批准数据</h3> <ul> <li ng-repeat="item in ctrl.approvedList"> 数量: {{item.count}} | 类型: {{item.type || '无'}} | 描述: {{item.desc || '无'}} </li> </ul> <h3>待处理数据</h3> <ul> <li ng-repeat="item in ctrl.pendingList"> 数量: {{item.count}} | 类型: {{item.type || '无'}} </li> </ul> <h3>已拒绝数据</h3> <ul> <li ng-repeat="item in ctrl.rejectedList"> 数量: {{item.count}} | 类型: {{item.type || '无'}} </li> </ul> <h3>需重新提交数据</h3> <ul> <li ng-repeat="item in ctrl.resubmitList"> 数量: {{item.count}} | 类型: {{item.type || '无'}} </li> </ul> </div>
小提示
- 如果你的AngularJS版本比较旧(1.5及以下),可能需要用
success/error代替then/catch,用法类似:$http.get('your-data-url') .success(function(data) { // 处理数据逻辑和上面一致 }) .error(function(error) { console.log('请求失败:', error); }); - 记得给
ng-app和ng-controller正确绑定,不然数据不会渲染到页面上哦~
内容的提问来源于stack exchange,提问作者Pritesh Naik
相关产品推荐
相关产品推荐

