I am developing a simple AngularJS application which authenticates a user and displays a list of transactions associated to the user. In addition, there is a dropdown which allows the user to filter the transactions by year. The combobox model is an array of values that I retrieve from my API through an AngularJS resource, but only after I have retrieved the current user. This is the code:
//retrieve the user
UserManagement.getCurrentUser().then(function (user) {
//retrieve the transactions
$scope.transactions = Transactions.query({
userid: user.UserName,
status: $scope.status
});
//retrieve the array for the dropdown
//and return a promise
return TimeFilters.get({
userid: user.UserName,
status: $scope.status,
timefilter: 'years'
});
}).then(function (years) {
//set a scope variable to the array to bind in the view
$scope.timefilters.years = years;
console.debug(years);
//set also the currently selected year
$scope.timefilters.currentYear = $scope.timefilters.years[0];
})
Even though I learned promises today and maybe I misunderstood something, this code seems straightforward.
The problem is that when I try to assign currentYear
to the first element of timefilters.years
, the assignment fails because the array is still empty, even if it shouldn't be, as I am trying to assign in the .then
function. The result is that the dropdown is populated with the years, but no year is selected.
What did I misunderstand here?
BTW, the resource calls return the expected data, so that is not the problem.
EDIT: just after posting I changed the return statement in the first then
to:
return TimeFilters.get({...}).$promise
and now it works as espected. But I thought that $resource.get was meant to return a promise already. I am really confused. Could someone clarify?