Coding an app with AngularJs. I want to retrieve a list of all groups a user has joined.
I wrote the following:
controller('DashCtrl', function($scope, $q, $localStorage, AuthService, DatabaseService, GroupService) {
console.log("*** DashCtrl ***");
var user = AuthService.currentUser;
$scope.user = user;
var uid = $scope.user.auth.uid;
$scope.joinedGroups = [];
var tmpGroups = [];
var addGroupDetailsPromises = [];
GroupService.getUserJoinedGroupsArray($scope.user.auth.uid)
.then(function(groups) {
for (var i = 0; i < groups.length; i++) {
var tmpGroup = {};
tmpGroup.id = groups[i];
addGroupDetailsPromises.push(addGroupDetails(tmpGroup));
tmpGroups.push(tmpGroup);
}
})
.catch(function(error) {
console.log('Error retrieving groups: ', error);
});
// Once all details have been added to groups, sort groups
$q.all(addGroupDetailsPromises).then(function() {
console.log(tmpGroups.length);
tmpGroups.sort(function(a, b) {
console.log('a: ', a.details.timestamp);
console.log('b: ', b.details.timestamp);
return a.details.timestamp - b.details.timestamp;
});
console.log(tmpGroups);
$scope.joinedGroups = tmpGroups;
}).catch(function(error) { console.log(error); });
function addGroupDetails(tmpGroup) {
var promise = new Promise(function(resolve, reject) {
GroupService.getGroupDetailsObj(tmpGroup.id).then(function(details) {
tmpGroup.details = details;
tmpGroup.display = {};
var eventDate = new Date(details.timestamp);
var today = new Date();
if (eventDate >= today) {
tmpGroup.display.day = eventDate.getDate();
tmpGroup.display.month = monthNames[eventDate.getMonth()].substr(0, 3);
tmpGroup.display.time = eventDate.getHours() + ":" + eventDate.getMinutes();
}
resolve();
});
});
return promise;
};
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
})
My array of groups (tmpGroups) never gets sorted. The length of the array equals 0 based on what outputs my console.log(tmpGroups.length)... I guess that is the reason why it never gets sorted.
But I don't understand that results because my array is supposed to be filled with all the information as I used $q.all that waits for all promises to be resolved.
Any suggestions ?
Thanks