我愿意检索资源请求的响应 header ,因为我已将分页信息和其他内容放入其中,而不是响应正文,以使 REST api 清晰。
虽然我们可以从成功/错误回调中得到它,如下所示:
Object.get({type:'foo'}, function(value, responseHeaders){
var headers = responseHeaders();
});
其中“对象”是我的资源工厂服务。
此外,当我在解决所需资源后尝试更改路线时,我已经尝试过:
.when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListCtrl',
// wait for the required promises to be resolved before controller is instantialized
resolve: {
objects: ['Object', '$route', function(Object, $route){
return Object.query($route.current.params).$promise;
}]
}
})
在 Controller 中,只需注入(inject)“对象”而不是对象服务,因为它已被解析并填充了真实数据。
但是当我尝试从 Controller 中的“对象”获取标题信息时遇到问题。
我试过
objects.$promise.then(function(data, responseHeaders){})
,但 responseHeader 未定义。如何更改 $resource 服务的行为,以便将 responseHeader getter 扔到 $promise then() 回调函数中?
我的服务“对象”供引用:
myServices.factory('Object', ['$resource',
function($resource){
return $resource('object/:id', {id: '@id'}, {
update: {method: 'PUT'},
});
}
]);
最佳答案
我有同样的问题。我在资源定义中使用了一个拦截器来在资源中注入(inject) http header 。
$resource('/api/resource/:id', {
id: '@id'
}, {
index: {
method: 'GET',
isArray: true,
interceptor: {
response: function(response) {
response.resource.$httpHeaders = response.headers;
return response.resource;
}
}
}});
然后,在
then
回调,http头可以通过$httpHeaders
访问:promise.then(function(resource) {
resource.$httpHeaders('header-name');
});
关于angularjs - 资源解析后,在 ngResource 对象的 $promise 属性的 then() 函数中获取响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898265/