我正在尝试在我的信息中心上添加热门帖子。获得顶级'捕获'即帖子不是问题,虽然使用Auth0,我需要将用户信息与相应的用户链接。
目前我在我的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。目前我正在获得一个承诺。如何将其转换为每个用户的dataObj。
答案 0 :(得分: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;
});
}
}]);