在 AngularJS $resource query() 之后如何找出列表中有多少条记录

How can I find out how many records are in the list after AngularJS $resource query()

我正在努力解决一些我认为应该非常简单的事情。

我想查看从 query() 返回了多少项,但使用长度对我不起作用。

这是我的代码

    getItems = function () {

        // retrieve the list
        theList = Users.query();
        theList.$promise.then(function (res) {
            console.log("success");
        })
        .catch(function (req) {
            console.log("error");
        })
        .finally(function () {

        });

        return theList;
    }

$scope.users = getItems();
console.log($scope.users.length);

这是我的$资源:

.factory('Users', function ($resource) {
    return $resource('https://example.com/:id', { id: '@id' }, {
        update: { method: 'PUT' }
    });
})

即使列表中有项目,控制台也会显示 0。

知道我做错了什么吗?

尝试

getItems = function () {

        // retrieve the list
        theList = Users.query();

        theList.$promise.then(function (res) {
            console.log("success");
            $scope.users = res;
            console.log($scope.users.length);
        })
        .catch(function (req) {
            console.log("error");
        });

    }

getItems();

您的 getItem() 正在返回承诺。所以从中提取列表,然后尝试你在 getItem();

中所做的长度
//try this
getItems().then(function(result) {
    $scope.users = result;
    console.log('result: %o', $scope.users.length);
})