我有以下资源:
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();
}).
我需要将响应标头中的游标从资源传递到控制器。有什么(干净的)方法可以做到这一点?
最佳答案
您可以将最后一个游标存储在工厂闭包中,并使用自定义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();
关于javascript - 将响应 header 从ngResource传递到 Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20428576/