【问题标题】:Multiple resource calls with promises in AngularJS在 AngularJS 中使用 Promise 调用多个资源
【发布时间】:2014-04-01 23:53:32
【问题描述】:

我正在开发一个简单的 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 语句更改为:

return TimeFilters.get({...}).$promise

现在它可以正常工作了。但我认为 $resource.get 是为了返回一个承诺。我真的很困惑。有人可以澄清一下吗?

【问题讨论】:

    标签: javascript angularjs ng-options ngresource


    【解决方案1】:

    Angular $resources docs有答案:

    重要的是要意识到调用 $resource 对象方法 立即返回一个空引用(对象或数组取决于 是数组)。一旦数据从服务器返回,现有的 参考是用实际数据填充的。

    还有:

    资源实例和集合有这些额外的 属性:

    $promise:创建的原始服务器交互的承诺 这个实例或集合。

    成功时,promise 会使用相同的资源实例解决,或者 集合对象,使用来自服务器的数据进行更新。

    因此,当调用 $resource.get() 时,确实希望得到类似空的 ObjectArray 的引用。只有使用$resource.get().$promise,您才会收到deisred promse 对象。

    【讨论】:

    • 谢谢。我想我的方法是唯一一种处理资源检索同步的方法,对吧? (除了使用回调,我不太喜欢)
    • 我使用的是$resource.get().$get(),它发出了重复的调用。使用$resource.get().$promise 解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2015-01-16
    • 1970-01-01
    • 2019-04-24
    • 2013-11-30
    相关资源
    最近更新 更多