未解决的承诺角度

时间:2015-08-17 16:36:32

标签: javascript angularjs

我使用ngResource将数据从服务器端获取到我的视图中,并且我有一个我定义的自定义操作可以获取项目数,它在代码(控制器)中看起来像这样:

$scope.totalItems = Item.item_count().total

在我看来:

This customer bought {{totalItems}}

在我看来,我只是得到了This customer bought而没有插入其他部分。但是当我这样做时:

console.log(Item.item_count().total)
console.log(Item.item_count())

我得到undefined作为第一个陈述但是第二个陈述我得到了这个:

enter image description here

为什么我无法从视图中访问总计数,我该怎么做才能解决这个问题?

更新(服务代码):

app.factory('Item', function($resource) {
  return $resource(
        window.config.API_URL + '/:apiPath/:id', {
            id: '@id',
            apiPath: '@apiPath'
        }, {
            query: {
                method: 'GET',
                params: {
                  apiPath: 'items'
                },
                isArray: true
            },
            item_count: {
                method: 'GET',
                params: {
                  apiPath: 'item_count'
                },
                isArray: false
            }
        }
    );
});

5 个答案:

答案 0 :(得分:4)

您需要获取$promise并传递回调,如下所示:

Item.item_count().$promise.then(function(data) {
  $scope.totalItems = data.total;
});

如果您需要在加载视图之前解析数据,可以使用$ stateProvider来解决它。这应该可以让您了解如何以及使用它的一些含义:http://www.codelord.net/2015/06/02/angularjs-pitfalls-using-ui-routers-resolve/

答案 1 :(得分:0)

看起来你得到了一个承诺。 尝试拨打console.log(Item.item_count().then(function(data) { console.log(data); });

答案 2 :(得分:0)

如果没有看到你的其他代码,我的猜测就是这条线 在承诺得到解决之前,$scope.totalItems = Item.item_count().total正在得到解决。那条线应该有点接受承诺。然而,这只是猜测,因为您还没有真正发布此代码。

答案 3 :(得分:0)

因为Item.item_count()会返回一个承诺,所以在设置$scope.totalItems之前必须等到它被解决:

Item.item_count().then(function(item_count) {
  $scope.totalItems = item_count.total;
});

答案 4 :(得分:0)

尝试从视图中的scope.中删除{{}}

This customer bought {{totalItems}}