2016-06-06 2 views
1

Я пытаюсь добавить верхнюю часть, размещенную на моей приборной панели. Получение верхних «захватов» aka сообщений не было проблемой, хотя работа с Auth0, мне нужно связать информацию о пользователе с соответствующими пользователями.Извлечение данных из обещаний | Angularjs

В настоящее время я получаю обещание в моем dataObj что я прохожу вдоль, чтобы проверить, кто сделал наибольшее количество голосов, но, видя, что это асинхронный У меня возникли проблемы при получении данных и положить его в пользователь переменные:

app.controller('dashboardCtrl', ['$scope', '$http', 'captureApi', 'userApi', 'filterFilter', '$q', function($scope, $http, captureApi, userApi, filterFilter, $q){ 
    $scope.captures = []; 
    $scope.pageSize = 4; 
    $scope.currentPage = 1; 

    $scope.topPosters = []; 



    captureApi.getAllCaptures().then(function(res) { 
     $scope.captures = res.data; 

     userApi.getUsers().then(function(res){ 

     $scope.getCount = function getCount(strCat){ 
       return filterFilter($scope.captures, {userId:strCat}).length; 
      };  

      var users = res.data.users; 
      var i; 
      for(i=0; i<users.length; i++) { 
       var userId = users[i].user_id; 
       console.log(userId); 
       console.log($scope.getCount(userId)); 

       $scope.user = userApi.getUser(userId).then(function(res){ 
        $scope.userInfo = res.data; 
        console.log($scope.userInfo); 
        return res.data; 
       }); 

       var dataObj = { 
        user : $scope.user, 
        userId : userId, 
        amountPosted : $scope.getCount(userId) 
        }; 

        $scope.topPosters.push(dataObj); 
      } 
      console.log($scope.topPosters[0].user); 
     }); 
    }); 
}]); 

Как вы можете видеть, я получаю все снимки, затем я считаю их в зависимости от их userId. Как только это будет сделано, я добавлю их в dataObj. Но в промежутке я пытаюсь добавить информацию о пользователе (используя userApi.getUser(ID), а также добавьте их данные в эти данные. В настоящий момент я получаю обещание. Как преобразовать это в dataObj каждого пользователя.

ответ

0

Попробуйте загрузить все данные перед нажатием на topPosters пример:..

app.controller('dashboardCtrl', ['$scope', '$http', 'captureApi', 'userApi', 'filterFilter', '$q', function ($scope, $http, captureApi, userApi, filterFilter, $q) { 
$scope.captures = []; 
$scope.pageSize = 4; 
$scope.currentPage = 1; 
$scope.topPosters = []; 

$scope.getCount = function getCount(strCat) { 
    return filterFilter($scope.captures, {userId: strCat}).length; 
}; 

$q.all({captures: getAllCaptures(), users: getUsers()}).then(function(collections) { 
    $scope.captures = collections.captures; 
    return collections.users; 
}).then(function (users) { 
    return $q.all(users.map(function (user) { 
     return getUserById(user.userId); 
    })); 
}).then(function (users) { 
    $scope.topPosters = users.map(function(user) { 
     //I think your user has propery "id" or similar 
     return { 
      user: user, 
      userId: user.id, 
      amountPosted: $scope.getCount(user.id) 
     } 
    }); 

    console.log($scope.topPosters); 
}); 

function getAllCaptures() { 
    return captureApi.getAllCaptures().then(function (res) { 
     return res.data; 
    }); 
} 

function getUsers() { 
    return userApi.getUsers().then(function (res) { 
     return res.data.users; 
    }); 
} 

function getUserById(userId) { 
    return userApi.getUser(userId).then(function (res) { 
     return res.data; 
    }); 
} 

}]); 
+0

Спасибо .. работал как шарм, я должен применять его с помощью этой METHODE более –

+0

мне было интересно, если я мог бы общаться с вами в режиме реального времени чтобы немного задать пару вопросов? –

+0

Skype: flamps1. Но у меня мало свободного времени, я работаю –

Смежные вопросы