如何获取从服务器(nodejs expressjs)到角度控制器的响应数据?

时间:2017-07-29 20:09:10

标签: angularjs httpresponse

$http
   .get('/getFollowings/' + currentUser)
   .success(function(response) {
        $scope.friendlist = response;
   });

我想得到响应的数据。但我无法单独处理这些值。 '回应'包含:

[{"_id":"597c9fabc1ada32277f1da34","following":[{"username":"him"},{"username":"ron"},{"username":"nadu"}]}]

我希望得到usernames

4 个答案:

答案 0 :(得分:2)

我建议使用lodash库,试试这个:

$scope.friendlist = _.chain(response.plain())
                     .map(function(item){
                        item.following = _.pluck(item.following,'username')
                        return item;
                     })
                     .pluck('following')
                     .flatten()
                     .value();

答案 1 :(得分:0)

您可以使用angular.forEach

$scope.usernames = [];
$http.get('/getFollowings/' + currentUser)
    .success(function(response) {
      $scope.friendlist = response;
      angular.forEach($scope.friendlist[0].following, function(val) {
          $scope.usernames.push(val.username)
      });
    });

此处$scope.usernames是一个包含用户名

所有值的数组

您可以使用ng-repeat在视图中显示这些值。

 var myApp = angular.module('myApp', []);
 myApp.controller('ctrl', ['$scope', function($scope) {
     var response = [{
         "_id": "597c9fabc1ada32277f1da34",
         "following": [{
             "username": "him"
         }, {
             "username": "ron"
         }, {
             "username": "nadu"
         }]
     }];
     $scope.usernames = [];
     angular.forEach(response[0].following, function(val) {
         $scope.usernames.push(val.username)
     });
 }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<div ng-repeat="username in usernames"><span>{{username}}</span></div>
</div>

答案 2 :(得分:0)

如果您使用$ http,则需要将Object提供给客户端。

结构:

{
  "data": [
    {
      "_id": "597c9fabc1ada32277f1da34",
      "following": [
        {
          "username": "him"
        },
        {
          "username": "ron"
        },
        {
          "username": "nadu"
        }
      ]
    }
  ]
}

在您的控制器中:

$scope.friendlist = response.data;
//i think it's simple
for(var i=0;i<$scope.friendlist.length;i++){
    console.log($scope.friendlist[i]);
}

答案 3 :(得分:0)

只需使用forEach循环从阵列中获取所有用户名。

    $scope.usernameList = [];
    $http
    .get('/getFollowings/' + currentUser)
    .success(function(response) {
       $scope.friendlist = response;           
       $scope.friendlist[0].following.forEach(function(item){
       $scope.usernameList.push(item.username);  
       });
   }); 

所以现在$scope.usernameList包含名为以下数组的所有用户名。