我正在开发一个简单的 AngularJS 应用程序,它对用户进行身份验证并显示与用户关联的事务列表。此外,还有一个下拉菜单允许用户按年份过滤交易。组合框模型是我通过 AngularJS 资源从我的 API 中检索的值数组,但只有在我检索到当前用户之后。这是代码:
//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];
})
尽管我今天学习了 Promise,也许我误解了一些东西,但这段代码看起来很简单。
问题是,当我尝试分配currentYear
的第一个元素时timefilters.years
,分配失败,因为数组仍然是空的,即使它不应该是,因为我试图在.then
函数中分配。结果是下拉列表中填充了年份,但没有选择年份。
我在这里误会了什么?
顺便说一句,资源调用返回预期的数据,所以这不是问题。
编辑:就在发布后,我将第一个返回语句更改then
为:
return TimeFilters.get({...}).$promise
现在它可以正常工作了。但我认为 $resource.get 是为了返回一个承诺。我真的很困惑。有人可以澄清一下吗?