Uic*_*one 12 rest angularjs angularjs-resource
我愿意检索资源请求的响应头,因为我在其中放入了分页信息和其他内容而不是响应主体,以使REST api清晰.
虽然我们可以从成功/错误回调中获取它,如下所示:
Object.get({type:'foo'}, function(value, responseHeaders){
var headers = responseHeaders();
});
Run Code Online (Sandbox Code Playgroud)
'Object'是我的资源工厂服务.
此外,当我尝试在解决所需资源后更改路由时,我尝试过:
.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;
}]
}
})
Run Code Online (Sandbox Code Playgroud)
并且在控制器中,只需注入"对象"而不是对象服务,因为它已经解析并填充了真实数据.
但是当我尝试从控制器中的"对象"获取头信息时,我遇到了问题.
我试过了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'},
});
}
]);
Run Code Online (Sandbox Code Playgroud)
Ben*_*uré 10
我有同样的问题.我在资源定义中使用了一个拦截器来在资源中注入http头.
$resource('/api/resource/:id', {
id: '@id'
}, {
index: {
method: 'GET',
isArray: true,
interceptor: {
response: function(response) {
response.resource.$httpHeaders = response.headers;
return response.resource;
}
}
}});
Run Code Online (Sandbox Code Playgroud)
然后,在then
回调中,可以通过$httpHeaders
以下方式访问http标头:
promise.then(function(resource) {
resource.$httpHeaders('header-name');
});
Run Code Online (Sandbox Code Playgroud)
我想我遇到了类似的问题:在POST一个新资源之后我需要获取响应的Location头,因为新资源的Id在服务器上设置然后通过这个头返回.
我通过引入我自己的承诺解决了这个问题:
app.factory('Rating', ['$resource',
function ($resource) {
// Use the $resource service to declare a restful client -- restangular might be a better alternative
var Rating = $resource('http://localhost:8080/courserater/rest/ratings-cors/:id', {id: '@id'}, {
'update': { method: 'PUT'}
});
return Rating;
}]);
function RestController($scope, $q, Rating) {
var rating = new Rating();
var defer = $q.defer(); // introduce a promise that will be resolved in the success callback
rating.$save(function(data, headers){ // perform a POST
// The response of the POST contains the url of the newly created resource
var newId = headers('Location').split('/').pop();
defer.resolve(newId)
});
return defer.promise;
})
.then (function(newId) {
// Load the newly created resource
return Rating.get({id: newId}).$promise; // perform GET
})
.then(function(rating){
// update the newly created resource
rating.score = 55;
return rating.$update(); // perform PUT
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13267 次 |
最近记录: |