将响应头从ngResource传递给控制器

时间:2013-12-06 16:14:40

标签: javascript rest angularjs ngresource

我有以下资源:

factory('User', function($resource) {
    return $resource(apiURL + 'user/:userId', {}, {
        query: {
            method: 'GET',
            isArray: true,
            transformResponse: function(data, headers) {
                data = JSON.parse(data);
                var cursor = headers().link;
                if(!cursor) {
                    return data;
                }
                data.cursor = getNextCursor(cursor);
                console.log(data);
                return data;
            }
        }
    });
}).

这是我的控制者:

controller('UserListCtrl', function($scope, $rootScope, User) {
    $scope.users = [];
    $scope.orderBy = 'created';
    $rootScope.title = 'user';
    var cursor;

    /**
     * Appends new results to the list of users.
     */
    function appendResults(results) {
        console.log(results);
        cursor = results.cursor;
        console.log('set cursor: ' + cursor);
        for(var i in results) {
            if(results[i] instanceof User) {
                $scope.users.push(results[i]);
            }
        }
    }
    /**
     * Fetches new users from the server and appends it to the
     * locally stored users.
     */
    $scope.fetch = function() {
        if(cursor) {
            console.log('using cursor:');
            User.query({ncursor: cursor}).$promise.then(appendResults);
        } else {
            User.query().$promise.then(appendResults);
        }
    };
    $scope.fetch();
}).

我需要将响应头中的光标从资源传递给我的控制器。有没有(干净的)方法呢?

1 个答案:

答案 0 :(得分:0)

您可以将最后一个光标存储在工厂闭合中,并使用自定义getter返回它。

更新资源:

factory('User', function($resource) {
    // the last responce cursor
    var _cursor;
    var resource = $resource(apiURL + 'user/:userId', {}, {
        query: {
            method: 'GET',
            isArray: true,
            transformResponse: function(data, headers) {
                // save cursor to closure variable
                _cursor = headers().link;
                return JSON.parse(data);
            }
        }
    });
    // custom getter
    resource.getCursor = function() {
        return _cursor
    }
    return resource;

}).

更新了控制器:

$scope.fetch = function() {
    if(User.getCursor()) {
        console.log('using cursor:');
        User.query({ncursor: User.getCursor()}).$promise.then(appendResults);
    } else {
        User.query().$promise.then(appendResults);
    }
};
$scope.fetch();