【问题标题】:Get the first item in a json array in angular?以角度获取json数组中的第一项?
【发布时间】:2014-04-30 10:39:45
【问题描述】:

我正在尝试从我与工厂调用的 Web 服务中获取 json 数组中的第一项。

我的控制器:

CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
   $scope.groups = GetGroups.getGroups();
   console.log($scope.groups);
   console.log($scope.groups[0]);
   $scope.group1 = $scope.groups[0];
}]);

我的服务:

'use strict';
var Groups = angular.module('GroupsService', ['ngResource']);

Groups.factory('GetGroups', ['$resource',
function($resource){
    return $resource('../../../api/Groups/GetGroups', {}, {
        getGroups : {method : 'GET', params:{}, headers: {'Accept': 'application/json;charset=UTF-8'}, isArray : true}
    });
}]);

“console.log($scope.groups);”返回:

[$promise: Object, $resolved: false]
0: Resource
    groupId: "361552"
    groupName: "1"
    __proto__: Resource
>1: Resource
>2: Resource
>3: Resource
>4: Resource
>5: Resource
$promise: Object
$resolved: true
length: 6
__proto__: Array[0]

虽然“console.log($scope.groups[0]);”只返回“未定义”。

有什么方法可以获取该对象中的第一项?

【问题讨论】:

  • getGroup 方法返回的是 promise 对象而不是数据。尝试使用 GetGroups.getGroups().then(response){ $scope.groups = response};
  • 谢谢你,我看到了一些关于这个的东西,但它给了我'TypeError:undefined is not a function'。知道那是什么意思吗?

标签: javascript json angularjs


【解决方案1】:

getGroup 正在返回一个承诺。试试这个。

CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
function($scope, GetGroups){
   GetGroups.getGroups()
    .then(function(data){
      $scope.groups = data;
    });
}]);

然后,当该请求被“解决”时,$scope.groups 将成为您从该请求返回的数据。

【讨论】:

  • 谢谢你,我看到了一些关于这个的东西,但它给了我'TypeError:undefined is not a function'。知道那是什么意思吗?
【解决方案2】:

试试这个。它的工作..

 CreateProjectIndex.controller('GroupCtrl', ['$scope', 'GetGroups',
    function($scope, GetGroups){
       $scope.groups = GetGroups.getGroups();
       $scope.groups.$promise.then(function(data) {
           alert(data[0].toSource());
       });

    }]);

【讨论】:

  • 谢谢你,我看到了一些关于这个的东西,但它给了我'TypeError:undefined is not a function'。知道那是什么意思吗?
  • 你能简单地发短信吗,在这种情况下你得到了 TypeError。
猜你喜欢
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 2020-08-23
相关资源
最近更新 更多