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

how to get data in response which getting from server(nodejs expressjs) to angular controller?

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

我想获取在 response.but 中我无法单独处理这些值的数据。 'response' 包含:

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

我想要这个usernames

我推荐使用 lodash 库,试试这个:

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

您可以使用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>

如果您使用的是 $http,则需要将对象提供给客户端。

结构:

{
  "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]);
}

只需使用 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 包含了下面命名的数组中的所有用户名。